镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

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

Description

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

Activity

  1. wvanvugt-speedline commented on Feb 5, 2021

    @wvanvugt-speedline

    This appears to be a duplicate of #41759

  2. IanVS commented on Jun 4, 2021

    @IanVS

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

    image

  3. RyanCavanaugh commented on Jun 11, 2021

    @RyanCavanaugh
    Member

    Confirmed fixed 4.2 -> 4.3

  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions