TypeScript user type guards / type predicates (x is Y)
I failed to understand user-defined type guard recently and wrote something like:
// Don't do this:
const dogs = animals.filter( (c: Cat | Dog): c is Dog => true )
Nope, that’s not what that a type predicate is for. The above expression does nothing.
I had Dave explain it to me. It’s an escape hatch for you to hack the type system. What you need to do is:
function isDog(animal: Cat | Dog): animal is Dog {
// Whatever you need to do to test the type
// Danger:
// The type system will take your word for this and will
// not check it further, so get it right!
return "woof" in animal;
}
// TypeScript will narrow the type using the above type predicate:
const dogs: Dog[] = animals.filter(isDog);I’ve shared a playground for that example, and the relevant documentation is: Using type predicates.