Discriminated union type guard destructuring destructured extracted assigned property
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;
}
}
Search Terms
Discriminated union type guard destructuring destructured extracted assigned property
Suggestion
If the discriminating property of an interface is assigned to a
constvia destructuring or directly it is not usable as a type guard.Use Cases
Examples
In the example I would expect
boolto be usable as a type guard in functionsfandgbut it is not. Is there something I am missing here that would make this unsound?https://www.typescriptlang.org/play/#src=interface%20A%20%7B%0D%0A%0D%0A%09bool%3A%20false%3B%0D%0A%7D%0D%0A%0D%0Ainterface%20B%20%7B%0D%0A%0D%0A%09bool%3A%20true%3B%0D%0A%0D%0A%09data%3A%20string%3B%0D%0A%7D%0D%0A%0D%0Atype%20C%20%3D%20A%20%7C%20B%3B%0D%0A%0D%0A%0D%0Afunction%20f(x%3A%20C)%20%7B%0D%0A%0D%0A%09const%20%7B%20bool%20%7D%20%3D%20x%3B%0D%0A%0D%0A%09if%20(bool)%20%7B%0D%0A%0D%0A%09%09return%20x.data%3B%0D%0A%09%7D%0D%0A%7D%0D%0A%0D%0A%0D%0Afunction%20g(x%3A%20C)%20%7B%0D%0A%0D%0A%09if%20(x.bool)%20%7B%0D%0A%0D%0A%09%09return%20x.data%3B%0D%0A%09%7D%0D%0A%7D
Checklist
My suggestion meets these guidelines: