Can another variable function as a type guard?
Consider the following code snippet:
let foo: string | null = Math.random() > .5 ? null : 'bar'
const otherProp = true
const test = foo !== null && otherProp
function foobar(x: string){}
If I were to call foobar(foo)
, I would expect a warning because foo can be null or a string, and only a string is allowed.
However, if I call it like this:
if (test){
foobar(foo)
}
It should not give me a warning because test is only true if foo is not null, meaning only a string remains as the type.
Is something like this achievable?