Using instanceof
The keyword instanceof
is an operator (similar to +
and &&
) which checks if the given object is an instance of a specified class.
The instanceof
operator comes from JavaScript, and TypeScript adds additional type narrowing in blocks that depend on the result of an instanceof
operation.
Loading TypeScript...
Try hovering over value
in the if
and else if
blocks above. You will notice that TypeScript infers that the type of value
is User
in the if
block, and Admin
in the else if
block.
If the TypeScript compiler isn't absolutely sure, it won't narrow the type. This can happen for variables declared with let
instead of const
, or in situations where instanceof
is computed outside the if
statement.