Search code examples
typescripttypechecking

Typescript: How to typecheck against a complex type?


I have some complex types:

type odds: 1 | 3 | 5 | 7 | 9;
type evens: 2 | 4 | 6 | 8 | 0

...and some function which takes those complex types:

function(digit: odds | evens) { ... }

I would like to check which type I'm getting, but none of the following work:

if (digit isntanceof odds) // error: odds refers to a type but is being used as a value
if (typeof digit === ???) // issue: no single value for typeof

.

How can I go about checking if digit is odd using types?


Solution

  • Types don't exist at compiler time so typeof will not work, you need some other type of check to test the type at runtime. Typescript has support for this using a custom type-guards

    type odds = 1 | 3 | 5 | 7 | 9;
    type evens = 2 | 4 | 6 | 8 | 0;
    function isOdd(v: odds | evens) : v is odds {
        return v % 2 != 0
    }
    
    declare let n: odds | evens;
    withEven(n) // invalid here no check has been performed
    withOdd(n) // invalid here no check has been performed
    if (isOdd(n)) {
        n // is typed as odd
        withEven(n) // invalid here
        withOdd(n) // valid here we checked it is odd
    } else {
        n // is typed as even
        withEven(n) // valid here we checked it is not odd
        withOdd(n) // invalid here
    }
    function withEven(n: evens) { }
    function withOdd(n: odds) { }