| Start |
|---|
| Type guarding functions You can declare functions that serve as type guards using any logic you'd like. They take the form: If the function returns true, TypeScript will narrow the type to For example (try it (opens new window)): A guard's function type predicate (the Type guard functions don't have to use For example, this code determines if you've got a jQuery object by checking for it's version string. |
| Using instanceof
This code (try it (opens new window)): prints to the console. |
| Using typeof
Unlike This code (try it (opens new window)): prints Syntax
RemarksUsing type annotations in TypeScript constrains the possible types your code will need to deal with, but it is still common to need to take different code paths based on the runtime type of a variable. Type guards let you write code that discriminates based on the runtime type of a variable, while remaining strongly typed and avoiding casts (also known as type assertions). |
Read Article
https://develop.horje.com/learn/1434/reference