Narrowing: refining types
In the previous lesson we saw that on a union you can only use what is common to all its members. So how do we use toUpperCase on a string | number value? The answer is narrowing: you write a normal JavaScript check and the compiler understands that, inside that branch, the type is more specific. There is no new syntax to learn, only checks you already know and that TypeScript knows how to read. It is one of the features that make the language feel natural.
typeof and truthiness checks
The most used tool is typeof. If you compare typeof value with 'string', inside the if the compiler treats value as a string; in the else, as whatever remains of the union. A truthiness check also works: if (name) rules out null and undefined, though be careful because it also rules out the empty string and zero. When you only want to rule out null or undefined, it is more precise to compare explicitly with !== undefined.
function format(value: string | number): string {
if (typeof value === 'string') {
return value.toUpperCase(); // value is string here
}
return value.toFixed(2); // value is number here
}
function greet(name: string | undefined): string {
if (name === undefined) {
return 'Hello, stranger';
}
return 'Hello, ' + name.trim();
}
console.log(format('abc'), format(3.14159));
console.log(greet(undefined), greet(' Ana '));The in operator and equality
When you have a union of objects, the in operator checks whether a property exists and narrows the type accordingly. Equality also narrows: if you compare two values with ===, TypeScript deduces they share a type inside that branch. And for unions of literals, a simple if or switch on the value is enough to know exactly which one it is in each branch.
type Cat = { meow: () => string };
type Dog = { bark: () => string };
function speak(pet: Cat | Dog): string {
if ('meow' in pet) {
return pet.meow(); // pet is Cat
}
return pet.bark(); // pet is Dog
}
type Light = 'red' | 'yellow' | 'green';
function action(light: Light): string {
switch (light) {
case 'red':
return 'stop';
case 'yellow':
return 'slow down';
case 'green':
return 'go';
}
}
console.log(speak({ meow: () => 'meow!' }), action('green'));Notice that action does not need a final return: the compiler checks that the switch covers all three possible cases. If later you add 'flashing' to Light and forget the case, TypeScript will flag an error in the function, because it could now end without returning anything. This exhaustiveness check is one of the biggest advantages of unions of literals, and we will strengthen it later with the never type.
A check that misleads is if (value) to decide whether a number exists. If value is 0, the condition is false even though the number is present, and your program will treat zero as if it were missing. For numbers and strings, compare explicitly with undefined or null. Likewise, typeof null returns 'object', a historical oddity of JavaScript, so to check objects you must rule out null separately. These traps are not TypeScript's but JavaScript's, yet the compiler helps you see them: if the narrowing is not what you expected, the type the editor shows will tell you right away.
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères