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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With