Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional discriminated union's callback parameter type is not inferred #35769

Closed
giladsegal opened this issue Dec 19, 2019 · 4 comments
Closed
Labels
Bug A bug in TypeScript
Milestone

Comments

@giladsegal
Copy link

giladsegal commented Dec 19, 2019

discriminated union

Code

type T1 = {
        as?: 'button',
        onClick?: (el: number) => void
} 

type T2 = {
        as: 'a',
        onClick?: (el: string) => void
}

type T = T1 | T2;

// onClick first parameter type is inferred according to T1 (number)
const myT1_1: T = {
        as: undefined,
        onClick: _ev => {}
}

// onClick first parameter type is inferred according to T1 (number)
const myT1_2: T = {
        as: 'button',
        onClick: _ev => {}
}

// onClick first parameter type is inferred according to T2 (string)
const myT2_1: T = {
        as: 'a',
        onClick: _ev => {}
}

// onClick first parameter type is not inferred (any)
const myT1_3: T = {
        onClick: _ev => {}
} 

Expected behavior:
onClick _ev parameter of myT1_3 is inferred to be a number

Actual behavior:
onClick _ev parameter of myT1_3 is any

Playground Link:
Playground Link

If the callback in T1 and T2 is replaced with a primitive member then myT1_3 is inferred correctly. Playground Link

@wvanvugt-speedline
Copy link

This appears to be a duplicate of #41759

@IanVS
Copy link

IanVS commented Jun 4, 2021

The parameter seems to be correctly inferred in the latest version of typescript, can this be closed as fixed?

image

@RyanCavanaugh
Copy link
Member

Confirmed fixed 4.2 -> 4.3

@wzono
Copy link

wzono commented Nov 18, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

5 participants