-
Notifications
You must be signed in to change notification settings - Fork 13k
Open
Labels
Help WantedYou can do thisYou can do thisPossible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some casesThe current behavior isn't wrong, but it's possible to see that it might be better in some cases
Milestone
Description
π Search Terms
contextual typing, discriminated unions
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries
- Tested with TS 5.4.5 and TS 5.9.2
β― Playground Link
π» Code
type NotWorkingUnion =
| ((value: number) => void)
| {
isString: true;
fn: ((value: string) => void);
}
| {
isString?: false;
fn: ((value: number) => void);
};
const test1: NotWorkingUnion = (a) => {}; // Works
const test2: NotWorkingUnion = { // Works
isString: true,
fn: (a) => {}
};
const test3: NotWorkingUnion = { // Works
isString: false,
fn: (a) => {}
};
const test4: NotWorkingUnion = { // Doesn't work!
fn: (a) => {}
};
type WorkingUnion =
| {
isString: true;
fn: ((value: string) => void);
}
| {
isString?: false;
fn: ((value: number) => void);
};
const test5: WorkingUnion = { // Works
isString: true,
fn: (a) => {}
};
const test6: WorkingUnion = { // Works
isString: false,
fn: (a) => {}
};
const test7: WorkingUnion = { // Works
fn: (a) => {}
};
π Actual behavior
Contextual typing breaks when an union is both discriminated by a field and one of the union variants is just a function
π Expected behavior
Contextual typing should correctly work, as the type system should have enough information to discriminate between a function and an object with or without the field
Additional information about the issue
strict
mode is enabled.
Metadata
Metadata
Assignees
Labels
Help WantedYou can do thisYou can do thisPossible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some casesThe current behavior isn't wrong, but it's possible to see that it might be better in some cases