Home > Blockchain >  Use TypeScript to extract narrowed object type
Use TypeScript to extract narrowed object type

Time:06-18

I have a type MyType that is equivalent to the following type definition:

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

How can I extract the type where foo is 'one', i.e.:

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

I am aware that I can do it programmatically, i.e.:

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

But I need the actual type definition, not the TS type inference.

CodePudding user response:

You can use MyType & {foo: 'one'} to achieve this. You're telling TS that foo is 'one', it can infer the type of the rest of the object from that.

CodePudding user response:

type MyTypeEquivalent = { foo: "one"; value: number } | { foo: "two"; value: string };

type Foo = Extract<MyTypeEquivalent, { foo: "one" }>;

This will make

type Foo = {
    foo: "one";
    value: number;
}
  • Related