You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Suggestion: Discriminate between union types based on extracted property #31870
Discriminated union type guard destructuring destructured extracted assigned property
Suggestion
If the discriminating property of an interface is assigned to a const via destructuring or directly it is not usable as a type guard.
Use Cases
Code brevity
Examples
In the example I would expect bool to be usable as a type guard in functions f and g but it is not. Is there something I am missing here that would make this unsound?
interface A {
bool: false;
}
interface B {
bool: true;
data: string;
}
type C = A | B;
function f(x: C) {
const { bool } = x;
if (bool) { // Error: Property 'data' does not exist on type 'C'. Property 'data' does not exist on type 'A'.
return x.data;
}
}
function g(x: C) {
const bool = x.bool;
if (bool) { // Error: Property 'data' does not exist on type 'C'. Property 'data' does not exist on type 'A'.
return x.data;
}
}
function h(x: C) {
if (x.bool) {
return x.data;
}
}
changed the title [-]Discriminate between union types based on extracted property[/-][+]Suggestion: Discriminate between union types based on extracted property[/+]on Jun 12, 2019
Is there something I am missing here that would make this unsound?
No, but this in general is difficult from an implementation standpoint - the compiler would have to track interactions between different variables. Basically right now the control-flow analyzer only considers what the expression inside if (...) implies for the variables directly involved in that expression. At that point it doesn't really know where, e.g. your bool variable actually originated from.
Activity
[-]Discriminate between union types based on extracted property[/-][+]Suggestion: Discriminate between union types based on extracted property[/+]jack-williams commentedon Jun 12, 2019
Tracked here #12184
fatcerberus commentedon Jun 13, 2019
No, but this in general is difficult from an implementation standpoint - the compiler would have to track interactions between different variables. Basically right now the control-flow analyzer only considers what the expression inside
if (...)implies for the variables directly involved in that expression. At that point it doesn't really know where, e.g. yourboolvariable actually originated from.typescript-bot commentedon Jun 15, 2019
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.