-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Closed
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
discriminate union export destructure destructuring
🕗 Version & Regression Information
- This is the behavior in every version I tried (including the nightly one), and I reviewed the FAQ for entries about (export, destructure, discriminate, union).
⏯ Playground Link
💻 Code
function acceptStringOnly(_x: string) { }
function acceptNullAndUndefinedOnly(_x: null | undefined) { }
function mutuallyEnabledPair<T>(value: T): {
enabled: true,
value: NonNullable<T>,
} | {
enabled: false,
value: null | undefined,
} {
if (null === value || undefined === value) {
return { enabled: false, value: null };
} else {
return { enabled: true, value };
}
}
const { enabled: E, value: V } = mutuallyEnabledPair("some string value");
if (E) {
V; // here it is string, ok
acceptStringOnly(V);
} else {
V; // here it is null | undefined, ok
acceptNullAndUndefinedOnly(V);
}
export const { enabled, value } = mutuallyEnabledPair("some string value")
if (enabled) {
value; // here it is string | null | undefined, weird
acceptStringOnly(value); // ERROR
} else {
value; // here it also is string | null | undefined
acceptNullAndUndefinedOnly(value); // ERROR
}🙁 Actual behavior
When variables are destructured from an object of a discriminated union type and they are exported, those variables lose their narrowed types defined by the discriminated union type. Meanwhile, if the variables are NOT exported, their narrowed types will be preserved, which is the expected behavior, whether the variables are exported or not.
🙂 Expected behavior
Preserve narrowed types for variables that are:
- Destructured from an object of a discriminated union type
- Exported.
Additional information about the issue
I guess this issue may be more or less related to this one.
whzx5byb
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