-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed
Closed
Copy link
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue
Milestone
Description
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.
SancheZz and elv1n
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue