Home > database >  exhaustive type checking in IF-statement
exhaustive type checking in IF-statement

Time:10-05

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!

CodePudding user response:

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';
}
  • Related