An unusual yet structurally sound code snippet is presented below:
function doFoo(food: string | null = null) {
food = food ?? getFood(); // getFood: () => string | null
if (!food) {
throw Error("There's still no food :(");
}
plate[food] = true;
}
Encountering the TypeScript error
Type 'null' cannot be used as an index type.ts(2538)
while trying to access plate[food]
, raises the question:
Is there a way to instruct TypeScript that the variable food
will never be null
when reaching that line?