Closed
Description
Search Terms
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;
}
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.