Skip to content

Record<Keys , ValueType>

Record 的作用是转换成 联合类型的属性键为 K,属性值为 T 的对象类型

实现

ts
type Record<K extends string, T> = {
  [PK in K]: T
}

栗子

ts
type CatNames = "miffy" | "boris" | "mordred"
type CatList = Record<CatNames, { age: number }>

const cats: CatList = {
  miffy: { age: 99 },
  boris: { age: 16 },
  mordred: { age: 600 },
}