6. ts中的泛型

  • <T> 泛型的作用:编写的时候不确定类型,当调用时确定类型

1. 单个泛型

  • 声明的时候需要用 <> 包裹起来
function createArray<T>(times: number, value: T): Array<T>{  // 根据对应参数的类型给T赋值
    let result = []
    for(let i = 0; i< times; i++){
        result.push(value)     
    }
    return result
}

let r = createArray(5, 'abc')
let r2 = createArray(5, 333)

2. 多个泛型

// 元组进行类型交换
const swap = <T, K>(tuple: [T, K]): [K, T] => { // 元组是特殊的数组
    return [tuple[1], tuple[0]]
}
let r = swap([{}, 'xx']); // => [123,'abc']  我能确定只有两项

3. 函数标注的方式

  • 类型别名
// 如果泛型不传参是unkown类型
type ICreateArray = <T>(x: number, y: T) => Array<T>;
const createArray: ICreateArray = <T>(times: number, value: T): Array<T> => {
    let result = [];
    for (let i = 0; i < times; i++) {
        result.push(value)
    }
    return result
}
createArray(3, 'abc');
  • 接口
interface ISum<T> { // 这里的 T 是使用接口的时候传入
    <U>(a: T, b: T): U // 这里的 U 是调用函数的时候传入
}
let sum: ISum<number> = (a:number, b:number) => {
    return 3 as any
}

4. 默认泛型

  • 可以指定泛型的默认类型,方便使用
interface T2<T = string>{
    name:T
}
type T22 = T2;
let name1:T22 = {name: 'Tom'}

5. 泛型约束

  • 主要强调类型中必须包含某个属性
// extends 约束,keyof 取当前类型的key,typeof 取当前值的类型
type withLen = { length: number }
const computeArrayLength = <T extends withLen, K extends withLen>(arr1: T, arr2: K): number => {
    return arr1.length + arr2.length
}
computeArrayLength('123', { length: 3 })  // 字符串有length属性
// computeArrayLength( 123, { length: 3 })  // 编译不通过,类型“number”的参数不能赋给类型“withLen”的参数,number没有length属性
const getVal = <T extends object, K extends keyof T>(obj: T, key: K) => {
    if (typeof obj !== 'object') {
        return
    }
}
type T1= keyof { a: 1, b: 2 };
type T2 = keyof string;
type T3 = keyof any; // string  |number | symbol

getVal({ a: 1, b: 2 }, 'a')

6. 类中的泛型

class GetArrayMax<T = number> { // [1,2,3] [a,b,c]
    public arr: T[] = [];
    add(val: T) {
        this.arr.push(val)
    }
    getMax():T {
        let arr = this.arr;
        let max = arr[0];
        for (let i = 1; i < arr.length; i++) {
            arr[i] > max ? max = arr[i] : null
        }
        return max;
    }
}
let arr = new GetArrayMax(); // 泛型只有当使用后才知道具体的类型
arr.add(1);
arr.add(2)
arr.add(3)
let r = arr.getMax()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容