xcatliu / typescript-tutorial

TypeScript 入门教程
https://ts.xcatliu.com
10.44k stars 1.33k forks source link

混合类型不适合放到类与接口章节,需要放到其他章节去讲 #119

Open xcatliu opened 4 years ago

xcatliu commented 4 years ago

混合类型

之前学习过,可以使用接口的方式来定义一个函数需要符合的形状:

interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    return source.search(subString) !== -1;
}

有时候,一个函数还可以有自己的属性和方法:

interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function (start: number) { };
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;