I was playing around with typescript and I noticed something unexpected.
I can see in showCarInfo2 function an error
Why can't I use function for non null assertions?
In the first function showCarInfo1 there is car.passengers !== null and everything works fine.
interface Car {
name: string;
passengers: string[] | null;
}
const car: Car = {
name: 'Seat',
passengers: ['Andrew', 'Kate'],
}
function showCarInfo1(car: Car) {
if(car.passengers !== null) {
console.log(`${car.name}${car.passengers.map(passenger => ` ,${passenger}` )}`)
} else {
console.log(car.name)
}
}
showCarInfo1(car)
const hasPassengers = (car: Car) => car.passengers !== null;
function showCarInfo2(car: Car) {
if(hasPassengers(car)) {
console.log(`${car.name}${car.passengers.map(passenger => ` ,${passenger}` )}`)
} else {
console.log(car.name)
}
}

x = foo !== null; if (x) { foo++}you'd still get an error. It's a common problem and a known issue. Walking through the transitive conditionals and inferring types through them is apparently very costly for the compiler.