打字稿 - 对象 OR

时间:2021-03-26 10:58:20

标签: typescript

我想要一个这样的类型:

如果存在属性 container,也期望属性 a。如果存在 item 属性,还需要属性 bcontaineritem 不能同时存在。

我假设的代码如下所示,但它似乎没有执行上述操作。

type A = { container: true; a: string } | { item: true; b: number };

如何构建这样的类型?


null | string 似乎意味着 null OR string,但 SomeObject | AnotherObject 似乎意味着 all properties present BOTH in SomeObject and AnotherObject

1 个答案:

答案 0 :(得分:1)

这可能看起来很笨拙,但基本上创建了一个 XOR。因此,如果您将 itemb 添加到变量 myVar,您将收到打字稿错误。

type ExampleType =
  | { container: true; a: string; item?: never; b?: never }
  | { item: true; b: number; container?: never; a?: never }

// Adding item or b to the below type, will cause a ts error
const myVar: ExampleType = { container: true, a: 'z' }

因此,如果提供了容器键,它将期望 a 的键值存在,如果传递了 item 或 b,则会出错。