typescript 如何定义一个OneOf类型?

interface Test {
    test: string
    name: string
    str: string
    num: number
}

type OneOf<T> = ...;

const test: OneOf<Test> = { num: 123 }; // 正确
const test: OneOf<Test> = { test: 'asdasd' }; // 正确
const test1: OneOf<Test> = { test: 'asdasd', name: 'namessss' }; // 错误
const test2: OneOf<Test> = { test: 2123 }; // 错误
const test3: OneOf<Test> = {}; // 错误

其实就是定义一个类型,这个类型指定的是某个对象类型其中一个键和值,只能是一个,不能为空,不能为多个,也不能值类型不对。
如何定义OneOf,interface也行

阅读 4.7k
1 个回答
type OneOf<T, P extends keyof T = keyof T> = { [K in P]-?: Required<Pick<T, K>> & Partial<Record<Exclude<P, K>, never>>; }[P];

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题