简体   繁体   English

Typescript - object 或

[英]Typescript - object OR

I'd like to have a type that says:我想要一种说:

If there's property container present, also expect property a .如果存在属性container ,则还期望属性a If there's item property present, also expect property b .如果存在item属性,则还需要属性b container and item cannot exist both at the same time. containeritem不能同时存在。

The code I'd assume would look as follows, but it doesn't seem to do the above.我假设的代码如下所示,但似乎没有执行上述操作。

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

How do I build such a type?我如何构建这样的类型?


null | string null | string seems to mean null OR string , but SomeObject | AnotherObject null | string似乎意味着null OR string ,但SomeObject | AnotherObject SomeObject | AnotherObject seems to mean all properties present BOTH in SomeObject and AnotherObject . SomeObject | AnotherObject似乎意味着all properties present BOTH in SomeObject and AnotherObject

This may seem hacky, but basically creates an XOR.这可能看起来很老套,但基本上创建了一个 XOR。 So if you were to add either item or b to the variable myVar , you would get a typescript error.因此,如果要将itemb添加到变量myVar ,则会收到 typescript 错误。

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' }

So say if the container key is provided, it will expect the key value for a to be present, and will error if item or b were passed.所以说如果提供了容器键,它将期望 a 的键值存在,并且如果传递了 item 或 b 则会出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM