Skip to main content

基本类型

基本类型

  • any
  • unknown
  • string
  • number
  • boolean
  • array
  • tuple
  • void
  • null
  • undefined
  • never

必看文献

提取object对象类型

const animal = { type: 'cat', name: 'Tom' };

type Animal = typeof animal;

提取object 的key作为类型

keyof typeof NpcDataRaw

提取数组元素类型

使用as const

利用 TypeScript 的类型推导特性,将数组声明为只读常量数组(使用 as const),然后通过索引类型查询来自动提取出联合类型,避免手动写入所有字符串。这种方式更加简洁且易于维护。

const directions = ["right", "rightTop", "top", "leftTop", "left", "leftBottom", "bottom", "rightBottom"] as const;

export type DirectionT = typeof directions[number];
type Animals = Array<{ type: string, name: string }>;

type Animal = Animals[number];

// 使用 infer
type Animal = Animals extends (infer T)[] ? T : never;

将string数组中的元素提取为常量类型

const valid_answers = ['yes', 'no', 'answer'] as const;

type Answer = (typeof valid_answers)[number];

const ans1: Answer = 'yes';// 没问题

const ans2: Answer = 'nope';// 编译不通过