Discovering the "is" Keyword in TypeScript
TypeScript…
I’ve been using TypeScript for a while now, but I never needed the is keyword—until recently. In a project, I had to handle different object types in a single function. TypeScript couldn’t figure out the types on its own, so I finally learned about user-defined type guards.
Here’s what I found:
is Keyword?The is keyword is used in type guard functions to narrow down types. For example:
typescriptfunction isCat(animal: Cat | Dog): animal is Cat { return (animal as Cat).meow !== undefined; }
This checks if the animal has a meow method. Inside the if block, TypeScript treats animal as a Cat. No more type confusion.
Honestly, it’s one of those features you don’t think about until you need it.
Here's the official documentation for it: TypeScript Handbook
Comments