TypeScript泛型接口(三)
以使用接口的方式来定义一个函数需要符合的形状:
interface SearchFunc { (source: string, subString: string): boolean; } let mySearch: SearchFunc = (source: string, subString: string) => { return source.search(subString) !== -1; }
当然也可以使用含有泛型的接口来定义函数的形状:
interface CreateArrayFunc { <T>(length: number, value: T): Array<T>; } let createArray: CreateArrayFunc = <T extends {}>(length: number, value: T): Array<T> => { let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } createArray(3, 'x'); // ['x', 'x', 'x']
进一步,我们可以把泛型参数提前到接口名上:
interface CreateArrayFunc<T> { (length: number, value: T): Array<T>; } let createArray: CreateArrayFunc<any>; createArray = function<T>(length: number, value: T): Array<T> { let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } createArray(3, 'x'); // ['x', 'x', 'x']
注意,此时在使用泛型接口的时候,需要定义泛型的类型。
相关推荐
zhangxiafll 2020-11-13
anglehearts 2020-08-17
xiaoxiaoCNDS 2020-06-25
TreasureZ 2020-06-16
lantingyue 2020-05-31
iconhot 2020-05-26
luohui 2020-04-29
fraternityjava 2020-04-29
yicuncuntu0 2020-04-19
Justhavefun 2020-02-21
alicelmx 2020-02-13
iconhot 2020-01-28
yicuncuntu0 2019-12-18
wxy0 2019-12-09
丁一鸣的CSDN 2011-06-25
iosJohnson 2019-11-05