Closed
Description
TypeScript Version: 3.4.0-dev.201xxxxx
Search Terms: Narrowing, "Tagged Unions"
Code
interface Square {
kind: 'square';
size: number;
}
interface Circle {
kind: 'circle';
radius: number;
}
type Shape = Square | Circle;
// works as expected (s.kind) does the correct narrowing
function areaWorking(s: Shape) {
switch (s.kind) {
case 'square': return s.size * s.size;
case 'circle': return Math.PI * s.radius ** 2;
}
}
// When saving s.kind to a const variable, narrowing does not work
function area(s: Shape) {
const {kind} = s; // same as const kind = s.kind;
switch (kind) {
case 'square': return s.size * s.size; // Property 'size' does not exist on type [Shape|Circle].
case 'circle': return Math.PI * s.radius ** 2; // Property 'radius' does not exist on type [Shape|Square].
}
}
Expected behavior:
I would expect to be able to pull the kind
property from the Shape
object into a const and the narrowing to work as expected.
Actual behavior:
Narrowing does not work, I need have the switch() go off of the variable passed in.
Playground Link: TS Playground
Related Issues: #18758
Metadata
Metadata
Assignees
Labels
No labels