In a TypeScript program, a variable can move from a less precise type to a more precise type. This process is called type narrowing. We can use type narrowing to avoid type errors like the one below:
function addLeg(animal: Animal) {
animal.legs = animal.legs + 1; // 💥 - Object is possibly 'undefined'
}
In this post, we are going to cover 6 different ways we can narrow types in TypeScript.
The Animal
type in the above example is as follows:
type Animal = {
name: string;
legs?: number;
};
TypeScript raises a type error because the legs
property in the addLeg
function because it could be undefined
, and it doesn’t make sense to add 1
to undefined
.
A solution is to check whether legs
is truthy before it is incremented:
function addLeg(animal: Animal) {
if (animal.legs) {
animal.legs = animal.legs + 1;
}
}
legs
is of type number | undefined
before the if
statement and is narrowed to number
within the if
statement. This type narrowing resolves the type error.
This approach is useful for removing null
or undefined
from types or removing literals from union types.
#typescript #programming