Type Guards and Differentiating Types | Typescript
To get the same code working, we'll need to use a type assertion:
User-Defined Type Guards#
A type guard is some expression that performs a runtime check that guarantees the type in some scope.
Using type predicates#
To define a type guard, we simply need to define a function whose return type is a type predicate:
pet is Fish is our type predicate in this example.
A predicate takes the form parameterName is Type, where parameterName must be the name of a parameter from the current function signature.
Any time isFish is called with some variable, TypeScript will narrow that variable to that specific type if the original type is compatible.
Notice that TypeScript not only knows that pet is a Fish in the if branch;
it also knows that in the else branch, you don't have a Fish, so you must have a Bird.
Using the in operator#
The in operator now acts as a narrowing expression for types.
typeof type guards#
instanceof type guards#
The right side of the instanceof needs to be a constructor function, and TypeScript will narrow down to:
- the type of the function's
prototypeproperty if its type is notany - the union of types returned by that type's construct signatures