Skip to content

Exhaustiveness checking doesn't work with variables #12668

Closed
@asyschikov

Description

@asyschikov

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:

  1. If I uncomment default then tsc believes that check is exhaustive.
  2. 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

No one assigned

    Labels

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions