在面向对象语言中,接口是一个很重要的概念,它的行为是抽象的,而具体如何行动需要类去实现。
TypeScript中的接口是一个非常灵活的概念,除了可用于对类一部分行为进行抽象外,也常用于对对象的形状进行描述。
接口示例 interface
interface Person {
name: string,
age: number
}
let jack: Person = {
name: 'jack',
age: 20
};
定义了一个接口Person,接着定义了一个变量jack,它的类型是Person,这样我们就约束了tom的形状必须和接口Person一致的,定义的变量比接口少一些属性是不允许,当然多一个属性也是不允许的。
由此可见,赋值的时候,变量的形状必须和接口保持一致。
可选属性和只读属性 ?
readonly
只读属性用于限制只能在对象刚创建的时候修改其值。
interface Person {
readonly name: string,
age?: number
}
let jack: Person = {
name: 'jack'
};
任意属性
interface Person {
readonly name: string,
age?: number,
[propName: string]: any
}
let jack: Person = {
name: 'jack'
};
// 使用[propName: string]定义了任意属性取string类型的值,
函数类型
接口能够描述js中对象拥有的各种外形。除了描述带有属性的普通对象外,接口也可以描述函数类型。
interface Search {
(strparent: string, str1: string): boolean
}
let search1: Search = function (strparent: string, str1: string): boolean {
return strparent.indexOf(str1) > -1;
};
类类型接口 implements
通过接口去约束类
简单示例
interface Action1 {
fly()
}
class Person1 implements Action1 {
fly() {
console.log('凹凸曼 飞飞飞');
}
}
let person1 = new Person1();
person1.fly();
一个类实现多个接口
interface Action1 {
fly()
}
interface Action2 {
swim()
}
class Person1 implements Action1, Action2 {
fly() {
console.log('凹凸曼 飞飞飞');
}
swim() {
console.log('凹凸曼不会游泳');
}
}
let person1 = new Person1();
person1.fly();
person1.swim();