TypeScript
typeof narrowing
Learn narrowing with typeof.
typeof narrowing
The typeof operator returns the runtime type of a value as a string. A check like typeof x === "string" in an if condition lets TypeScript narrow the type; inside the block x is treated as just string. This is the most common tool for branching on union types.
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase(); // string
}
return value.toFixed(2); // number
}
typeof return values
typeof possible return values: "string", "number", "bigint", "boolean", "symbol", "undefined", "function", "object". As a historical quirk, typeof null returns "object"; not null. So for null checks use === null.
function len(x: string | null): number {
if (x === null) return 0;
return x.length; // string
}
typeof null; // "object" (historical)
typeof undefined; // "undefined"
Exercise Handle a union type with typeof
Write a function format(value: string | number): string. If typeof value === "string", return value.toUpperCase(); otherwise return value.toFixed(2). To demonstrate, call console.log(format("hello")) and console.log(format(42)).
Show example solution
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}
console.log(format("hello"));
console.log(format(42));
Test yourself
-
What type does the condition typeof x === "number" narrow x to inside an if block?
- string
- "number" (string literal)
- any
- number
Show answer
number — The check typeof x === "number" narrows x to the number type; inside the condition x is treated as a number and number methods are available.
-
Narrowing with typeof
function upper(v: string | number): string {
if (typeof v === ____) {
return v.toUpperCase();
}
return v.toFixed(0);
}
Show answer
function upper(v: string | number): string {
if (typeof v === "string") {
return v.toUpperCase();
}
return v.toFixed(0);
}
-
typeof narrowing parts
- typeof operatörü
- returns runtime type string
- "string"
- typeof value of string type
- "object"
- typeof value of object including null
- if (typeof v === ...)
- provides type narrowing
Next lesson: in operator