typescript-tutorial icon indicating copy to clipboard operation
typescript-tutorial copied to clipboard

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

Open xcatliu opened this issue 5 years ago • 0 comments
trafficstars

混合类型

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

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;

xcatliu avatar Mar 02 '20 09:03 xcatliu