Type Guards
About
A type guard is TS technique to get information about a type of a variable. I think that type checking cannot be done cleanly without type guards.
TypeScript has some built-in JS operators like typeof
, instanceof
, and the in
operator. Type guards allows the TS compiler to infer a specific type for a variable.
Type guards are typically used for narrowing down a type.
There are five major ways to use a type guard:
The
instanceof
keywordThe
typeof
keywordThe
in
keywordEquality narrowing type guard
Custom type guard with predicate
The instanceof
Type Guard
instanceof
Type Guardinstanceof
are used to check if a value is an instance of a given constructor function or class.
TS is also aware of the context within
if
andelse
, so that we can narrow down types.
The typeof
Type Guard
typeof
Type GuardThe typeof
type guard is used to determine the type of a variable, but is said to be very limited. It can only determine the following types recognized by JS:
boolean
string
bigint
symbol
undefined
function
number
For anything not on the list, the typeof
will return object
.
The syntax is like this:
typeof v === 'typename'
typeof v !== 'typename'
where typename
can be a string
, number
, symbol
, or boolean
.
The in
Type Guard
in
Type GuardThe in
type guard checks if an object has a particular property, using it to differentiate between different types.
The syntax is like this:
propertyName in objectName
Equality Narrowing Type Guard
Equality narrowing checks for the value of an expression.
For two variables to be equal, both variables must be of the same type. If the type of a variable is not known, but it's equal to another variable with precise type, then TS will narrow the type of the first variable with the information the second variable provides.
Custom Type Guard with Predicate
This method is what I find the most interesting among the five major type guard techniques.
It's basically creating a function to check whether a variable belongs to a type and return a boolean result.
This method is the most powerful of all, but is also error-prone if you're not careful with how you define the function.
Enum Type Checks with Type Guards
Custom type guards are especially useful when checking types for a variable in enum array.
Be careful not to use in
keyword instead of includes
. Those two are totally different from each other!
REF
Last updated