函數接口
- 我們除了可以通過接口來限定對象以外, 我們還可以使用接口來限定函數
interface SumInterface {
(a: number, b: number): number
}
let sum: SumInterface = function (x: number, y: number): number {
return x + y;
}
let res = sum(10, 20);
console.log(res);
混合類型接口
- 約定的內容中, 既有對象屬性, 又有函數
-
如果這個時候我有一個需求,就是要求定義一個函數實現變量累加
-
分別來看看,沒有使用
混合類型接口
之前不同的實現方案 -
方式一(會污染全局空間)
let count = 0;
function demo() {
count++;
console.log(count);
}
demo();
demo();
demo();
- 方式二(使用閉包)
- 使用閉包確實可以解決污染全局空間的問題, 但是對於初學者來說不太友好
let demo = (() => {
let count = 0;
return () => {
count++;
console.log(count);
}
})();
demo();
demo();
demo();
- 方式三(利用 JS 中函數的本質)
- 在 JS 中函數的本質就是一個對象,然后我們就可以直接給該對象添加一個
count
屬性進行累加 - 第三種方式在 TS 當中進行編寫是會報錯的,要想在 TS 當中進行使用就需要使用到
混合類型接口
,如果想要驗證第三種方式可以新建一個 JS 文件在其中進行編寫和運行即可
let demo = function () {
demo.count++;
}
demo.count = 0;
demo();
demo();
demo();
使用混合類型接口
interface CountInterface {
(): void
count: number
}
let getCounter = (function (): CountInterface {
let fn = <CountInterface>function () {
fn.count++;
console.log(fn.count);
}
fn.count = 0;
return fn;
})();
getCounter();
getCounter();
getCounter();
- 如上代碼
CountInterface
接口要求數據既要是一個沒有參數沒有返回值的函數, 又要是一個擁有count
屬性的對象 fn
作為函數的時候符合接口中函數接口的限定():void
fn
作為對象的時候符合接口中對象屬性的限定count:number