What is TypeScript narrowing?
October 27, 2023
In TypeScript, narrowing refers to refining the type of a variable so that TypeScript understands it to be more specific than its initial type. This guide walks you through the various methods of type narrowing available in TypeScript.
typeof type guards
One of the most basic ways to narrow a type in TypeScript is using the
typeof operator. This is especially useful for distinguishing between primitive types.
instanceof type guards
When dealing with classes and object types, the
instanceof operator helps in narrowing.
User-defined type guards
You can also define your own type guards using a function. The return type of this function should be a type predicate,
parameterName is Type.
Literal type guards
When working with literal types, simple conditional checks can act as type guards.
Sometimes, you might be certain that a value is non-null or non-undefined, even though TypeScript thinks otherwise. The non-null assertion operator
! can be used in such scenarios.
A powerful way of narrowing types in TypeScript is using discriminated unions. These involve creating objects with a common literal property that TypeScript can check to narrow down the type.
Using in operator
in operator checks for the existence of a property in an object and can be used as a type guard.
Using assert functions
Introduced in TypeScript 3.7, assertion functions allow you to define a function where the returned type is asserted to be a more specific type.
In conclusion, narrowing in TypeScript is a versatile tool to make the type system more expressive and safe. By leveraging the different techniques of narrowing, developers can write more robust and type-safe code.
How to fix the "not all code paths return a value" issue in TypeScript
Working with WebSockets in Node.js using TypeScript
Type Annotations Can Only Be Used in TypeScript Files
Guide to TypeScript Recursive Type
How to Configure Knex.js with TypeScript