Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exhaustive type checking in IF-statement

Tags:

typescript

I read up about exhaustive type checking and it is really a great feature of typescript. I experimented with it and came across some odd behavior (or not fully implemented by the typescript team). This is the code I have now (which works great):

type factType = 'test-1' | 'test-2'

function doSomething(fact: factType) {
    if (fact ==='test-1') {
        return true;
    } else if(fact === 'test-2') {
        return true;
    }

    assertUnreachable(fact);
}

function assertUnreachable(x: never): never {
    throw new Error("Didn't expect to get here");
}

But when I use a function as a branching condition, it breaks. It says "Argument of type 'string' is not assignable to parameter of type 'never' fact: "test-2"":

type factType = 'test-1' | 'test-2';

function doSomething(fact: factType) {
    if (fact === 'test-1') {
        return true;
    } else if (isTest2(fact)) {
        return true;
    }

    assertUnreachable(fact);
}

function isTest2(fact: factType) {
    return fact === 'test-2';
}

I tried using fact as 'test-2' but it does not work. Does anyone know how to fix this or what the reason may be? I think it is Typescript, but I am by no means an expert!

Thanks!

like image 347
Robbe Claessens Avatar asked Jun 21 '26 21:06

Robbe Claessens


1 Answers

Use a type predicate to indicate to TS that the function checks if fact is of type test-2.

function isTest2(fact: factType): fact is 'test-2' {
    return fact === 'test-2';
}
like image 116
Taxel Avatar answered Jun 23 '26 10:06

Taxel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!