0%
如何使用interface 為函數定義參數型別與回傳值型別
1 2 3 4 5 6 7
| interface SearchFunc { (source: string, subString: string): boolean; }
interface customVariables { variableA: boolean; }
|
如何使用interface 定義”可索引類型”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| interface arrayType { [index: number]: string; }
interface readonlyArrayType { readonly [index: number]: string; }
interface arrayType { [index: string]: number; value:string }
|
使用implement 將class與 interface 對接
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| interface ClockInterface { currentTime: Date; setTime(d: Date): void; }
class Clock implements ClockInterface { currentTime: Date = new Date(); setTime(d: Date) { this.currentTime = d; } constructor(h: number, m: number) { } }
|
如何快速定義一個class的constructor 參數型別與其建立出來的實例型別?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| interface ClockConstructor { new (hour: number, minute: number); }
interface ClockInterface { tick(); }
const Clock: ClockConstructor = class Clock implements ClockInterface { constructor(h: number, m: number) {} tick() {
} }
|
interface也可以extend
實際使用起來就跟class的extend 差不多
1 2 3 4 5 6 7 8 9 10 11 12 13
| interface Shape { color: string; }
interface Square extends Shape { sideLength: number; }
let square = <Square>{};
square.color = "blue"; square.sideLength = 10;
|
interface extend class? 用意是什麼?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Control { private state: any; }
interface SelectableControl extends Control { select(): void; }
class Button extends Control implements SelectableControl { select() { }
class TextBox extends Control { select() { } }
class Image implements SelectableControl { select() { } }
|