instanceof and in Narrowing
Narrow class instances and object shapes.
Welcome
`instanceof` narrows class instances and `in` narrows object types based on property presence. Both are essential for working with complex unions.
instanceof Narrowing
Use `instanceof` to check if a value is an instance of a class. TypeScript narrows the type to that class.
function handle(err: Error | string) {
if (err instanceof Error) {
console.log(err.message); // err: Error
} else {
console.log(err); // err: string
}
}All lessons in this course
- typeof and Truthiness Narrowing
- instanceof and in Narrowing
- User-Defined Type Guard Functions
- Exhaustiveness Checking with never