官网地址,本文也是参考官网来写:https://ts.xcatliu.com/advanced/generics.html
借用官网的话:在定义函数、接口或类的时候,不预先指定具体的参数类型,而在被调用时候再指定类型的一种特性。
接下来就探讨怎么用
function createArray<T>(length: number, value: T): Array<T> { let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } // 调用函数时指定输出数据为stringz console.log(createArray<string>(3, ‘x‘)); // [‘x‘, ‘x‘, ‘x‘] // 如果不指定,就自动根据传入参数类型决定输出数组内容类型 console.log(createArray(3, true)); // [true, true, true]
占个坑,后续慢慢填上,等有空继续补充
原文:https://www.cnblogs.com/konghaowei/p/14373990.html