Typescript: Wrong function return type inference (union type parameter)

Created on 14 Nov 2019  路  4Comments  路  Source: microsoft/TypeScript

TypeScript Version: 3.8.0-dev.20191114


Search Terms: Wrong union type parameter function result type inference

Code

interface ITestRequired {
    key: string
    ignoredKey: string
}

interface ITestOptional {
    key?: string
    ignoredKey?: string
}

export const unwrapTestObject = ({ key }: ITestRequired | ITestOptional) => ({ key })

// testObj is of ITestRequired type
const testObj: ITestRequired = {
    key: 'test',
    ignoredKey: 'test'
}

const testFilter = unwrapTestObject(testObj)

// testFilter.key should always be a string here, but instead we get
// testFilter.key is possibly 'undefined'.
console.log(testFilter.key.substring(0, 2))

Expected behavior:
Output type should be inferred from input type even when using Union types (because it is specified in the parameter type).

Actual behavior:
Parameter type is totally ignored.

Playground Link

Related Issues:
Did not find anything similar.

Most helpful comment

Are you looking for generic functions?

All 4 comments

Are you looking for generic functions?

@AnyhowStep like so ?

export const unwrapTestObject = <T>({ key }: T) => ({ key })

indeed it seems to do the job, but I'm getting Property 'key' does not exist on type 'unknown'. as I'm trying to destructure the parameter (seems like TS generics and destructuring are not friends from what I could find in the issues).

Playground Link

More like

const unwrapTestObject = <T extends ITestOptional>({ key }: T): Pick<T, "key"> => ({ key })

The compiler is working as intended (the compiler doesn't distribute control flow analysis over union types); you might consider closing this issue. Good luck!

That's a bit complicated but thanks it's working !
I was simply hoping for something more "generic" ^^

Because I simplified this for the example, but I have to do this with objects of 50 keys or more.

So i need to put them all in the Pick, which looks like shit once it's done.

Sorry I opened a bug report for this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

blendsdk picture blendsdk  路  3Comments

uber5001 picture uber5001  路  3Comments

jbondc picture jbondc  路  3Comments

manekinekko picture manekinekko  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments