keyof typeof

7 阅读1分钟

当你有一个具体的对象值(比如配置表),你想从它“反推”出键名联合类型,就用:

keyof typeof obj = obj 这个对象的所有 key 的联合类型

例子:

const STATUS_TEXT = {
  idle: '空闲',
  loading: '加载中',
  success: '成功',
} as const

type Status = keyof typeof STATUS_TEXT
// Status = 'idle' | 'loading' | 'success'

在项目里会怎么用

  • 做配置表并约束变量只能取这些 key
  • const status = ref<Status>('idle')(不能写成 'xxx')

一句话记忆: