Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript inferencing with process.exit

Tags:

typescript

Normally, TypeScript can infer the type of a variable with the help of a guard follow by a return:

type Pet = Dog | Cat;
function isDog(pet: Pet): pet is Dog {
  return true;
}

function fn1(pet: Pet) {
  if (isDog(pet)) {
    return;
  }

  // At this point, TS knows that `pet` is a `Cat`.
}

However, if I were to change the return to process.exit, this does not work anymore:

function fn2(pet: Pet) {
  if (isDog(pet)) {
    process.exit(1);
  }

  // At this point, we know that `pet` should be a `Cat`, but TS doesn't know.
}

Is there a way for me to signal to the compiler that the program would have ended after process.exit, in a similar fashion as return?

Of course, I could just add a return after process.exit. However, in my actual code, my function is returning something, call it MyObject, such that there is no reasonable value for when pet is a Dog, hence the forceful exit.

I am aware that I could do some type assertions to get around this, but wondering what is a good way to solve this.

like image 759
yihangho Avatar asked Jan 26 '23 06:01

yihangho


1 Answers

I believe it's a limitation of Typescript (even the latest version).

Workaround:

You can return process.exit(1).

type Pet = Dog | Cat

function isDog(pet: Pet): pet is Dog {
    return true
}

function fn1(pet: Pet) {
    if (isDog(pet)) {
        return process.exit(1)
    }

    return console.log(pet)
}

Typescript infers pet to be a Cat.

screenshot of code

like image 192
Noel Llevares Avatar answered Feb 05 '23 01:02

Noel Llevares