概述
这是我学习typescript的笔记。写这个笔记的缘由主要有2个,一个是熟悉相关的写法;另外一个是理清其中一些晦涩的东西。供之后开发时参考,相信对其余人也有用。html
学习typescript建议直接看中文文档或英文文档。我是看的英文文档。git
typescript handbook 学习笔记2typescript
interfaces接口
类接口
interface SquareConfig { //标准写法 label: string; //可选属性 color?: string; //只读属性 readonly x: number; //缺省属性 [propName: string]: any; } //使用接口 function createSquare(config: SquareConfig): {color: string; area: number} { //用config.color这个形式调用 } //跳过额外属性检查的方法一:类型断言(强制跳过) let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig); //跳过额外属性检查的方法二:赋给变量(自动跳过) let squareOptions = { colour: "red", width: 100 }; let mySquare = createSquare(squareOptions);
其它接口
//函数接口,参数名不重要 interface SearchFunc { (a: string, b: string): boolean; } //使用函数接口,注意参数中的: string能够省略。 let mySearch: SearchFunc; mySearch = function(source: string, substring: string): boolean { let result = source.search(substring); return result > -1; } //可索引的接口(数字索引) interface StringArray { [index: number]: string; } //使用可索引接口 let myArray: StringArray; myArray = ['Bob', 'Fred']; let myStr: string = myArray[0]; //使用数字索引+字符串索引时,数字索引的类型须要是字符串索引的类型的子类型 iterface NumberDictionary { [index: string]: number; //字符串索引 readonly [index: number]: number; //只读数字索引,必须为number的子类型 length: number; //ok name: string; //error }
实现接口
接口只会检查类的实例属性,不会检查类的静态属性。因此不会检查constructor。若是constructor要用接口检查的话,须要额外给它定义一个接口,以下所示:ide
//额外定义constructor接口 interface ClockConstructor { new (hour: number, minute: number): ClockInterface; } interface ClockInterface { tick(); } function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface { return new ctor(hour, minute); } class DigitalClock implements ClockInterface { constructor(h: number, m: number) { } tick() { console.log("beep beep"); } } class AnalogClock implements ClockInterface { constructor(h: number, m: number) { } tick() { console.log("tick tock"); } } let digital = createClock(DigitalClock, 12, 17); let analog = createClock(AnalogClock, 7, 32);
继承接口
interface Shape { color: string; } interface PenStroke { penWidth: number; } //继承用extends,实现类用implements。 interface Square extends Shape, PenStroke { sideLength: number; } //接口的另外一种写法。实现一个对象。为何不用:? let square = <Square>{}; square.color = "blue"; square.sideLength = 10; square.penWidth = 5.0;
混合接口
//既能够当作函数接口,又能够当作类接口 interface Counter { (start: number): string; interval: number; reset(): void; } //当作函数接口 let counter01 = <Counter>function(start: number) {}; //当作类接口 let counter02 = <Counter>{}; counter02.interval = 2; counter02.reset();
继承类的接口
class Control { private state: any; } interface SelectableControl extends Control { select(): void; } //error,须要先继承Control才能实现接口SelectableControl class Image implements SelectableControl { select() { } } //OK class Button extends Control implements SelectableControl { select() { } }