Skip to content

CFA for destructured discriminated unions failed with generic constraintsΒ #50206

Closed
@whzx5byb

Description

@whzx5byb

Bug Report

πŸ”Ž Search Terms

CFA, destructure, discriminated union, generic

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

Here are two examples taken from #46266. Either of them works well.

type Action =
    | { kind: 'A', payload: number }
    | { kind: 'B', payload: string };

function f10({ kind, payload }: Action) {
    if (kind === 'A') {
        payload.toFixed();
    }
    if (kind === 'B') {
        payload.toUpperCase();
    }
}

function f11(action: Action) {
    const { kind, payload } = action;
    if (kind === 'A') {
        payload.toFixed();
    }
    if (kind === 'B') {
        payload.toUpperCase();
    }
}

However, when the argument action is not a certain type, but a generic type with a constraint, only the latter works.
I'm not sure whether it is a bug but I believe these two functions should have the same behavior.

type Action =
    | { kind: 'A', payload: number }
    | { kind: 'B', payload: string };

function _f10<T extends Action>({ kind, payload }: T) {
    if (kind === 'A') {
        payload.toFixed(); // doesn't work
    }
    if (kind === 'B') {
        payload.toUpperCase(); // doesn't work
    }
}

function _f11<T extends Action>(t: T) {
    const { kind, payload } = t;
    if (kind === 'A') {
        payload.toFixed();
    }
    if (kind === 'B') {
        payload.toUpperCase();
    }
}

πŸ™ Actual behavior

CFA fails in _f10

πŸ™‚ Expected behavior

No error.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions