Closed
Description
TypeScript Version: 2.0.3
Code
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Square | Rectangle;
function area(s: Shape) {
// // Doesn’t compile: Using a `const` as a type guard:
// // `error TS2339: Property 'size' does not exist on type 'Shape'.`
// const isSquare = s.kind === 'square';
// if (isSquare) {
// return s.size * s.size;
// }
// // `s` is not narrowed to type `Rectangle`
// Compiles: Directly using `s` in the type guard:
if (s.kind === 'square') {
return s.size * s.size; // `s` has type `Square`
}
// `s` is narrowed to type `Rectangle`
return s.width * s.height;
}
Expected behavior:
s
’s type can be narrowed indirectly via a const
.
Actual behavior:
s
’s type can only be narrowed via direct access.