Sub topic 3
Narrowing with typeof
This chapter covers the typeof guard. It is the first built-in narrowing construct and the one you will use most often for primitive values. It assumes you can read TypeScript union types such as string | number, and that you know if, switch and the ternary operator. The previous chapter explained that control flow analysis narrows a value inside a branch. Here you will see that process work with typeof.
What typeof does at runtime and at compile time
typeof is a JavaScript operator. It runs at runtime and returns one of eight strings.
| Value | `typeof` result |
|---|---|
| `"hi"` | `"string"` |
| `42` | `"number"` |
| `10n` | `"bigint"` |
| `true` | `"boolean"` |
| `Symbol()` | `"symbol"` |
| `undefined` | `"undefined"` |
| `null`, `{}`, `[]` | `"object"` |
| `() => {}` | `"function"` |
TypeScript has a second, unrelated use of the word. In a type position, typeof config means "the type of the variable config". This chapter is only about the runtime operator used in an expression, such as typeof value === "string".
The compiler recognizes comparisons between a typeof expression and one of those eight strings as a type guard. Inside the branch where the comparison is true, the variable has the matching type. In the other branch, the compiler removes that type from the union.
The basic pattern
This example narrows string | number in both directions.
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}Inside the if, value is string, so toUpperCase is allowed. The branch returns, so control flow analysis knows that code after the if is reached only when the check failed. There value is number, and toFixed is allowed.
Without the check, both calls are errors. toUpperCase does not exist on number, and toFixed does not exist on string. A method is callable on a union only if every member has it.
Equivalent shapes
The compiler follows several ways of writing the same check. These all narrow in the same way.
ifwith an early return, as above.if/else, where theelsebranch holds the remaining types.- A ternary:
typeof v === "string" ? v.length : v. - Negation:
typeof v !== "string"narrows the true branch to the other members. &&and||chains:typeof v === "number" && v > 0.
In a && chain, the right side is checked with the narrowed type from the left side. That is why typeof v === "number" && v > 0 compiles even when v is string | number.
Narrowing more than two types
Each typeof check removes one member. Several checks in sequence peel the union down.
function toLabel(value: string | number | boolean): string {
if (typeof value === "string") {
return value;
}
if (typeof value === "number") {
return value.toString();
}
return value ? "yes" : "no";
}At the last line, value is boolean, because string and number have both been eliminated.
You can also use switch (typeof value). Each case clause is treated as a typeof check.
function describe(value: string | number | boolean): string {
switch (typeof value) {
case "string":
return `text of length ${value.length}`;
case "number":
return `number ${value.toFixed(1)}`;
default:
return value ? "yes" : "no";
}
}In the default clause, value is boolean.
Narrowing unknown
typeof is the main way to work with unknown. A value of type unknown allows almost nothing until you check it. Each typeof check turns it into a concrete type for the duration of that branch.
function toNumber(input: unknown): number {
if (typeof input === "number") {
return input;
}
if (typeof input === "string") {
return Number(input);
}
throw new TypeError("Expected a number or a string");
}This works well for primitives. For objects, typeof input === "object" only tells you that the value is some non-function object, or null. You need further checks to learn its shape. Those are covered in the chapters on the in operator and on user-defined type guards.
Narrowing functions
A typeof check against "function" separates callable members from the rest.
function resolveText(source: string | (() => string)): string {
return typeof source === "function" ? source() : source;
}This is a common pattern for options that accept either a value or a factory.
Be careful with generics. If the union includes a bare type parameter, as in T | (() => T), the compiler cannot rule out that T is itself a function, so the narrowing is imprecise. Use a concrete type when you can.
Pitfall: typeof null is "object"
This is a historical quirk of JavaScript. typeof null returns "object", and TypeScript models it faithfully. A typeof check for "object" therefore keeps null in the narrowed type.
function joinOrEmpty(value: string | string[] | null): string {
if (typeof value === "object") {
// value is string[] | null here
if (value === null) {
return "";
}
return value.join(", ");
}
return value;
}After the typeof check, the true branch holds string[] | null. The extra null check is required. Without it, value.join is an error under strictNullChecks. In the code after the if, value is string.
Pitfall: typeof does not exclude NaN
typeof NaN is "number". TypeScript has no separate type for it, so a typeof check cannot rule it out. If your function must reject NaN, add a runtime check such as Number.isNaN(value). The compiler will not narrow on it.
Pitfall: only literal strings count
The compiler narrows when the comparison involves one of the eight known strings. If you compare against a variable, narrowing does not happen.
const expected: string = "string";
function broken(value: string | number): string {
if (typeof value === expected) {
// value is still string | number here
return String(value);
}
return String(value);
}The type of expected is the wide type string, so the compiler cannot tell which member to keep. Write the literal in the comparison.
A misspelled string is caught for you. In typeof value === "strnig", the compiler reports that the comparison appears to be unintentional, because "strnig" is not one of the possible typeof results.
Narrowing literal and enum-like unions
typeof works on the base primitive, so it narrows unions of literals as well. Given "left" | "right" | number, the check typeof v === "string" narrows to "left" | "right". It cannot distinguish "left" from "right". For that you need an equality check, which is the topic of a later chapter.
Storing the check in a variable
You can name the result of a typeof check and use it later, if the condition is a const and the narrowed variable is a const, a readonly property or a parameter that is never reassigned.
function lengthOf(value: string | string[]): number {
const isText = typeof value === "string";
return isText ? value.length : value.length;
}Here the two value.length expressions are both valid. In the true branch value is string, and in the false branch it is string[]. If the variable is reassigned anywhere in the function, this aliasing stops working, so prefer writing the typeof check inline when in doubt. The chapter on the limits of narrowing explains why.
When typeof is not enough
Use typeof for primitives and for the function case. Reach for another tool in these situations.
| Situation | Better tool |
|---|---|
| Distinguishing `null` from an object | `value === null` |
| Telling arrays from other objects | `Array.isArray(value)` |
| Telling class instances apart | `instanceof` |
| Choosing between object shapes | `in` operator or a discriminant property |
| Validating an `unknown` object | A user-defined type guard |
Summary of the working model
typeofreturns one of eight strings at runtime, and the compiler uses a comparison against a literal string as a type guard.- The true branch keeps the matching type. The false branch removes it.
- Early returns,
elsebranches, ternaries,&&chains andswitch (typeof x)all narrow. typeof nullis"object", so a check for"object"must be followed by a null check.NaNis anumber, andtypeofcannot exclude it.- The comparison must use a literal string for narrowing to occur.
Exercise
The function below fails to compile with the error "'value' is possibly 'null'" on the line that calls trim. Explain why, and show a fix that keeps the typeof check.
function clean(value: string | null): string {
if (typeof value === "object") {
return "";
}
return value.trim();
}
Show answer
The check is the wrong way round for what the author wants, and it also hides a quirk. typeof null is "object", so the true branch holds null, and the code after the if has value narrowed to string. In this exact code the compiler accepts value.trim() after the if, so the reported error would come from a variant such as one that returns inside the string branch. The reliable fix is to check for null directly and use typeof only for the primitive: if (typeof value === "string") { return value.trim(); } return "";. Checking typeof value === "string" is clear and avoids the null quirk, because null is removed by the false branch and the true branch is exactly string.
Exercise
Write a function sum(input: number | string | number[]): number that returns the number itself, the parsed number for a string using Number(...), and the total of the elements for an array. Which checks do you use, and why is typeof input === "object" a poor choice for the array case?
Show answer
Use typeof input === "number" to return the number, typeof input === "string" to return Number(input), and treat what remains as number[]: return input.reduce((total, n) => total + n, 0);. Here typeof input === "object" would work for this particular union, because after the other two checks only the array is left, but it is a poor general choice. It is also true for null and for every other object type, so it would let those through if the union grew. Array.isArray(input) states the intent and stays correct if new object types are added.