Tuple to Object(easy)

62 阅读1分钟

Tuple to Object 将 tuple 类型转为对象类型。

as const 将变量标记为不可变。

typeof 一个不可变的数组会得到一个 tuple 类型。

T[number]会得到一个联合类型。

图片.png

声明一个泛型

type TupleToObject = any;

该泛型接受一个泛型参数 T

type TupleToObject<T> = any;

限制 T 的类型为 tuple

type TupleToObject<T extends readonly PropertyKey[]> = any;

用 T[number] 获取 T 的联合类型,再用 in 遍历

type TupleToObject<T extends readonly PropertyKey[]> = {
    [Key in T[number]]: Key;
};