Skip to content

方括号操作符

获取对象类型对应键的值的类型

ts
type User = {
  readonly id: number;
  name: string;
  age: number;
};
type UserName = User["name"]; // string
type UserAge = User["name" | "age"]; // string | number
type ValueType = User[keyof User]; // 获取值的类型,string | number
// 泛型
type ReadonlyKey<T> = {
  readonly [key in keyof T]: T[key];
};

获取数组元素的类型

ts
const arr = ["admin", "user", "client"] as const; // as const 变成元组
const arr2 = [1, true, "hello"];
type ArrType = (typeof arr)[number]; // "admin" | "user" | "client"
type FirstArrType = (typeof arr)[0]; // "admin"
type IndexArrType = (typeof arr2)[0]; // number | boolean | string,无法确定第一个元素属于哪个类型
/**
 * 获取元组类型的
 */
type ArrTupleType<T extends readonly any[]> = T[number];
type A = ArrTupleType<typeof arr>; // string

获取数组的长度

ts
const arr = ["admin", "user", "client"] as const;
type ArrLengthType = (typeof arr)["length"]; // 3
let n: ArrLengthType = 3;
/**
 * 获取元组类型的长度
 */
type ArrLength<T extends readonly any[]> = T["length"];

结合keyof 获取对象类型属性值的类型

集合泛型使用扩展运算符

ts
// Concat 合并数组
type Concat<T extends any[], U extends any[]> = [...T, ...U];
type ConcatArr = Concat<[1, 2], [3, 4]>; // [1, 2, 3, 4]

Released under the MIT License.