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

CFA for destructured discriminated unions failed with generic constraints #50206

Closed
whzx5byb opened this issue Aug 6, 2022 · 0 comments Β· Fixed by #50221
Closed

CFA for destructured discriminated unions failed with generic constraints #50206

whzx5byb opened this issue Aug 6, 2022 · 0 comments Β· Fixed by #50221
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@whzx5byb
Copy link

whzx5byb commented Aug 6, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
3 participants