typeScript中的接口--函数类型接口、可索引接口、类类型接口

函数类型的接口 批量函数类型的接口

interface encrypt{
    (key:string,value:string):string //参数key string类型 参数value string类型,函数返回值string类型 
}
var md5 = function(key:string,value:string):string{
    return key+value
}
var md6 = function(key:string,value:string):string{
    return key+' 1111 '+value
}
console.log(md5('名字','刘莉'))
console.log(md6('密码','234'))

可索引接口

var arr:number[]=[333,2,3,4,5,6]//子项都是number类型
var arr2:Array=['111','222']//另一种写法

1、数组的接口,定义索引的数据类型

interface UserArray{
     [index:number]:string
}
let arr:UserArray = ['aaa','bbb']
console.log(arr[1])

2、对象的接口

interface UserObj{
    [index:string]:string
}
let obj:UserObj = {name:'liuli',age:'333'}
console.log(obj.age)

类类型接口 (用到多)对类的约束和抽象类有点相似

interface Animal{
    name:string;
    eat(str:string):string;
}
class Dog implements Animal{
    name:string;
    constructor(name:string):string{
        this.name = name;
    }
    eat(str:string){
        return this.name+'吃'+str
    }
}
let d1 = new Dog('小黑');
console.log(d1.eat('骨头'));

class Cat implements Animal{
    name:string;
    constructor(name:string):string{
        this.name = name;
    }
    eat(){
        return this.name+'吃鱼头'
    }
}
let c1 = new Cat('小花猫');
console.log(c1.eat());

你可能感兴趣的:(typeScript中的接口--函数类型接口、可索引接口、类类型接口)