简体   繁体   English

使用 TypeScript 提取缩小的对象类型

[英]Use TypeScript to extract narrowed object type

I have a type MyType that is equivalent to the following type definition:我有一个MyType类型,它等效于以下类型定义:

type MyTypeEquivalent = { foo: 'one', value: number } | { foo: 'two', value: string }

How can I extract the type where foo is 'one' , ie:如何提取foo'one'的类型,即:

type DesiredExtractedType = { foo: 'one', value: number }

I am aware that I can do it programmatically, ie:我知道我可以以编程方式进行,即:

if (obj.foo === 'one') {
  obj.value // <-- type will be number
}

But I need the actual type definition, not the TS type inference.但我需要实际的类型定义,而不是 TS 类型推断。

You can use MyType & {foo: 'one'} to achieve this.您可以使用MyType & {foo: 'one'}来实现这一点。 You're telling TS that foo is 'one' , it can infer the type of the rest of the object from that.您告诉 TS foo'one' ,它可以从中推断出对象其余部分的类型。

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

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