Home > Back-end >  How do I get the type of one side of a union object?
How do I get the type of one side of a union object?

Time:05-17

I was tring to discern the type of a value returned by a 3rd party library. Unfortunately the type was the left hand side of a non-discriminated union, and was anonymous (i.e. not labeled).

See example below:

// given an anonymous return type from a non-discriminated union...
const someFn = function(): ({ colour: string, flavour: string } | Error) {
    return { colour: 'blue', flavour: 'blue' }
}

// how do I extract the left hand side type?
type Flavour = FlavourOrError[0]

CodePudding user response:

(TIL) I was able to discern the type, by using the ReturnType from the function.

And then using Extract to get the left hand side type.

If anyone knows a better way of doing this, please let me know!

// 1. get the return type of the function...
type ReturnUnion = ReturnType<typeof someFn>

// 2. extract the left hand side type, using a sample field...
type LeftHandSideType = Extract<ReturnUnion, { colour: string }>

// 3. later, use duck typing...
const value = someFn()
if (typeof (value as LeftHandSideType).colour !== 'undefined') {
    // do something with it...
}

CodePudding user response:

I don't see why you can't use the "regular JavaScript" way and check if the returned value was an error:

const value = someFn();

if (!(value instanceof Error)) {
    // do something with it...
}

This works just as well, without using ReturnType and Extract. However, if the return type of someFn is more complicated in your real code, then it might be more desirable to use ReturnType with Extract.

  • Related