函数类型接口
接口不仅可以描述 JavaScript 中对象的各种外形,也可以描述函数类型。
interface SearchFn {(source: string, subString: string): boolean;}let mySearch: SearchFn;mySearch = function (source, subString) {let res = source.search(subString);return res > -1;}// 以前篇章的写法 很冗余let oldMySearch: (source: string, subString: string)=> boolean = function (source, subString) {let res = source.search(subString);return res > -1;}
可索引类型接口
- 支持两种索引签名: 字符串和数字
- 索引签名类似于领导的意思
- 索引签名可以设置为只读 ```typescript interface StringArr {
}
let arr: StringArr; arr = [“aa”, “bb”];
// 特殊: number 来当索引时,JS 会将它转换为字符串去索引 interface Person { [propName: string]: string; // fouce on this name: string; age: number; // -> 报错 只能为string类型 }
<a name="SNghU"></a>## 类类型实现接口类类型实现接口,关键字: implement,类需要实现接口中的属性和方法。 <br />对比抽象类,关键字: abstract,抽象类只需要实现其中的抽象方法,其他是可以继承的。```typescriptinterface IClock { // 在这里定义类型currentDate: Date;setDate(d: Date): void;}// 关键字 implementclass Clock inplement IClock { // 在这里实现currentDate: new Date();setDate (d: Date) {this.currentDate = d;}}
类的静态部分实现
interface IDoor {name: string;open(): void;close(): void;}class Door implement IDoor {name = "amazingDoor";// constructor 是在类的静态部分,所以不再检查范围内;constructor (num: number) {}open () {console.log("welcom");}close() {console.log("bye");}}// 我们可以抽离一个函数的 interface 来实现检查 constructorinterface DoorConstructor {new(num: number): any;}function creatDoor (D: DoorConstructor, num: number) {return new D(num);}let aDoor = createDoor();
接口继承
接口跟类一样,接口也可以相互继承。
interface Alarm {Tip(): void;}interface Door extends Alarm {color: string;open(): void;close(): void;}let securityDoor = {} as Door;securityDoor.color = "white";securityDoor.open = () => {};securityDoor.Tip = () => {};securityDoor.close = () => {};
接口也可以继承类 ( 不建议这样写 )
class Point {x: number;y: number;constructor (x: number, y: number) {this.x = x;this.y = y;}}interface Point3D extends Point {z: number;}let ponit3D: Point3D = {x: 0,y: 0,z: 0}
