Here's the TypeScript code I'm working with:
let a: unknown = true;
if(hasColour(a)) {
console.log(a.colour); // Using a.colour after confirming a has the colour property
}
I've created a function to check if the color property exists:
function hasColour (obj: any) : boolean {
return !!obj &&
"colour" in obj &&
typeof obj == "object"
}
An error is popping up saying:
Cannot use 'in' operator to search for 'colour' in true.
To fix this, instead of specifying boolean as the return type, specify:
obj is { colour: string }
like so:
function hasColour (obj: any) : obj is { colour: string } {
return !!obj &&
"colour" in obj &&
typeof obj == "object"
}
Why does this work? Shouldn't hasColour return a true/false? Why does it work with obj is { colour: string }
as a return type?