题目:只允许单一键赋值(a、b 成立,c 报错)

给你一个 test 对象,利用它生成一个类型 Test2,要求:

  • a、b 可以赋值给 Test2
  • c 不能赋值给 Test2
const test = { SUCCESS: 100, FAIL: 500 }

// 令 a,b 成立,c 不成立
const a: Test2 = { FAIL: 500 }
const b: Test2 = { SUCCESS: 100 }
const c: Test2 = { SUCCESS: 100, FAIL: 500 } // 期望报错

答案

type Test2 = {
  [K in keyof typeof test]: {
    [P in K]: (typeof test)[K]
  } & {
    [P in Exclude<keyof typeof test, K>]?: never
  }
}[keyof typeof test]

来源整理自:vue3js.cn 面试官系列