Search code examples
typescriptdiscriminated-union

Typescript Tagged Unions - Can the compiler warn you about missed branch cases?


I'm new to TypeScript. I've got the following code:

type Circle = { kind: "circle" }
type Rectangle = { kind: "rectangle" }
type Triangle = { kind: "triangle" }
type Shape = Circle | Rectangle | Triangle

function numberOfSides(shape: Shape) {
    switch (shape.kind) {
        case "circle": return 0;
    }
}

Currently this compiles fine. Is there any configuration or option so the compiler can warn me that I'm missing cases in my switch statement?


Solution

  • Yes, you just need two things - 1. turn on strictNullChecks or noImplicitReturns. 2. Mark numberOfSides' return type as Number. At that point the compiler will catch that you are not dealing with all the cases and give you this error:

    Function lacks ending return statement and return type does not include 'undefined'.