Type narrowing is the process of refining a variable’s type within a conditional block of code.

this allows you to write more precise type-safe code.

TypeScript provides several mechanisms for narrowing types:

Type Guards

A type guard is a TypeScript technique used to get information about the type of a variable, usually within a conditional block. Type guards are regular functions that return a Boolean, taking a type and telling TypeScript if it can be narrowed down to something more specific. Type guards have the unique property of assuring that the value tested is of a set type depending on the returned Boolean.

TypeScript uses built-in JavaScript operators like typeof, instanceof, and in to determine if an object contains a property. Type guards enable you to instruct the TypeScript compiler to infer a specific type for a variable in a particular context. This process validates that the type of an argument aligns with the specified type, enhancing type accuracy and code reliability.

Type guards are typically used for narrowing a type and are quite similar to feature detection, allowing you to detect the correct methods, prototypes, and properties of a value. Therefore, you can easily figure out how to handle that value.

The instanceof type guard

image.png

instanceOf is a built-in type guard that can be used to check if a value is an instance of a given constructor function or class. With this type guard, we can test if an object or value is derived from a class, which is useful for determining the type of an instance type.

The basic syntax for the instanceof type guard is below:

image.png

image.png

The typeof type guard

image.png

The The typeof type guard is used to determine the type of a variable. The typeof type guard is said to be very limited and shallow; it can only determine the following types recognized by JavaScript: