TS范型函数
2022年11月7日
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
/** * 创建范型函数 * @param value */ function genericFunctions<Type>(value: Type): Type { return value } const genericFunctions0 = <T, N>(value: T, num?: N): T | N => { return value } /** * 调用范型函数 */ console.log( genericFunctions(10), //简化调用 genericFunctions0('22222', 111), //简化调用 genericFunctions<number>(10), //传统调用 genericFunctions0<string, number>('22222', 111), //传统调用 ) /** * 范型约束 必须是一个数组 */ function ids<Type>(value: Type[]): Type[] { console.log(value.length) return value } ids([1,2,3,4]) interface ILength { length: number } //创建一个接口 /** * Type extends ILength 添加泛型约束 * 解释:表示传入的 类型 必须满足 ILength 接口的要求才行,也就是得有一个 number 类型的 length 属性 * @param value */ function id<Type extends ILength>(value: Type): Type { console.log(value.length) return value } /** * keyof 是一个关键字 * @param obj * @param key */ function getProp<Type, Key extends keyof Type>(obj: Type, key: Key) { return obj[key] } let person = {name: 'jack', age: 18} console.log(getProp(person, 'name')) /** * keyof 是一个关键字 * @param obj * @param key */ function getProperty<Type extends object, Key extends keyof Type>(obj: Type, key: Key) { return obj[key] } console.log(getProperty(person, 'age')) |