TypeScript · Lesson 16 of 42
Narrowing with typeof, truthiness and equality checks
See how TypeScript narrows a union to a specific type inside if statements using typeof, truthiness, equality, Array.isArray and early returns.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will turn a union such as string | number | null into one specific type, using checks you already know from JavaScript. This is the skill that makes unions practical, and it is called narrowing.
The idea
When you check what a value is, the compiler narrows its type inside the code that the check protects. You do not write special syntax. The ordinary if is enough:
function describe(value: string | number): string {
if (typeof value === "string") {
return `text of length ${value.length}`;
}
return `number ${value.toFixed(1)}`;
}
console.log(describe("hello"));
console.log(describe(3.14159));text of length 5
number 3.1Inside the if, value is a string. After it returns, the only possibility left is number, so the compiler treats value as a number in the rest of the function. This follows the real flow of your code, which is why it is called control flow analysis.
typeof checks
typeof returns one of a small set of strings: "string", "number", "boolean", "bigint", "symbol", "undefined", "object" and "function". The compiler understands comparisons against all of them. A classic trap is that typeof null is "object", so an object check does not exclude null:
function keys(value: object | null): string[] {
if (typeof value === "object") {
return Object.keys(value);
}
return [];
}example.ts(3,24): error TS2769: No overload matches this call.
Overload 1 of 2, '(o: {}): string[]', gave the following error.
Argument of type 'object | null' is not assignable to parameter of type '{}'.
Type 'null' is not assignable to type '{}'.
Overload 2 of 2, '(o: object): string[]', gave the following error.
Argument of type 'object | null' is not assignable to parameter of type 'object'.
Type 'null' is not assignable to type 'object'.The compiler is right: inside that if, value could still be null. (Some compiler versions print a shorter message that shows only the last overload; the cause is the same.) Compare with null directly to exclude it.
Equality checks
Comparing with === or !== narrows to the compared value, and it works between two variables, too:
function label(value: string | null | undefined): string {
if (value === null) {
return "no value";
}
if (value === undefined) {
return "not set";
}
return value.toUpperCase();
}
console.log(label(null), label(undefined), label("ok"));no value not set OKA loose check value == null is true for both null and undefined, and it narrows both away at once. Some teams use it for exactly that purpose, and some forbid loose equality entirely. Pick one rule and stay consistent.
Truthiness checks
An if (value) check narrows away values that are falsy: null, undefined, false, 0, "" and NaN. That is convenient for optional strings and objects, but it hides a trap. A valid 0 or an empty string is removed too:
function showCount(count: number | undefined): string {
if (count) {
return `count is ${count}`;
}
return "no count";
}
console.log(showCount(5), showCount(undefined), showCount(0));count is 5 no count no countThe result for 0 is probably a bug: zero is a real count. When the value could legitimately be zero or empty, compare with undefined explicitly:
function showCount(count: number | undefined): string {
if (count !== undefined) {
return `count is ${count}`;
}
return "no count";
}
console.log(showCount(5), showCount(undefined), showCount(0));count is 5 no count count is 0Array.isArray
Because typeof reports arrays as "object", use Array.isArray to tell arrays from other values. The compiler understands it:
function toList(input: string | string[]): string[] {
if (Array.isArray(input)) {
return input;
}
return [input];
}
console.log(toList("a"), toList(["b", "c"]));[ 'a' ] [ 'b', 'c' ]Early returns keep code flat
You do not need an else. After a check that returns, the rest of the function has the narrowed type. This "guard clause" style avoids deeply nested code:
function discount(price: number | null, percent?: number): number {
if (price === null) {
return 0;
}
if (percent === undefined) {
return price;
}
return price * (1 - percent / 100);
}
console.log(discount(null), discount(80), discount(80, 25));0 80 60Narrowing has limits
Narrowing follows what the compiler can see. If you store a check in a variable, or if a function call might change the value, the narrowing may be lost. When the compiler cannot follow your logic, a user-defined type guard (next lesson) gives it the missing fact.
Common mistakes
Using truthiness for numbers and strings. 0 and "" are valid values that a truthiness check removes. Compare explicitly.
Using typeof to exclude null. typeof null is "object". Use === null.
Checking arrays with typeof. Use Array.isArray.
Expecting narrowing to survive a callback. Narrowing of a changing variable may not carry into a function created later. Copy the narrowed value into a const first.
Exercise
Write function len(value: string | string[] | null): number that returns the string length, the array length, or zero for null, using at least two kinds of check. Write function percent(value: number | undefined): string that returns "n/a" for undefined and "0%" for zero, avoiding the truthiness trap. Test with 0, 5 and undefined.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.