-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed
Labels
SuggestionAn idea for TypeScriptAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it adds
Description
TypeScript Version: 2.1.1
If you have exhaustiveness checking where a result is a return from a function it works.
But if result is assigning value to a variable exhaustiveness checking basically does nothing.
Code
interface Square { kind: "square"; size: number; }
interface Rectangle { kind: "rectangle"; width: number; height: number; }
interface Circle { kind: "circle"; radius: number; }
interface Triangle { kind: "triangle"; side: number; }
type Shape = Square | Rectangle | Circle | Triangle;
function area(s: Shape): number {
let area;
switch (s.kind) {
case "square": area = s.size * s.size; break;
case "rectangle": area = s.width * s.height; break;
case "circle": area = Math.PI * s.radius * s.radius; break;
case "triangle": area = Math.sqrt(3) / 4 * s.side * s.side; break;
//default: area = -1; break;
}
//Error because area is number | undefined
return area;
}
function areaWrapped(s: Shape): number {
let area;
area = (() => {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.width * s.height;
case "circle": return Math.PI * s.radius * s.radius;
case "triangle": return Math.sqrt(3) / 4 * s.side * s.side;
}
})();
return area;
}
Expected behavior:
Function area
: variable aria
should be number
because the check is exhaustive.
Sidenotes:
- If I uncomment
default
thentsc
believes that check is exhaustive. areaWrapped
uses IIFE to achieve the same effect and it works.
Actual behavior:
Variable area
is of type number | undefined
while it can't be undefined
.
Metadata
Metadata
Assignees
Labels
SuggestionAn idea for TypeScriptAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it adds