typeof narrowing
- TypeScript course
- Advanced
- Lesson 25/57
- 4 min
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"Practice 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)).
Starter code
// format(value: string | number): string fonksiyonunu typeof ile yaz
// string ise toUpperCase, sayı ise toFixed(2) ile döndür
// format("hello") ve format(42) sonuçlarını yazdırSample 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));Expected output
HELLO 42.00
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What type does the condition typeof x === "number" narrow x to inside an if block?
- string
- "number" (string literal)
- any
- number Correct answer
Explanation: 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.
2 Narrowing with typeof
function upper(v: string | number): string {
if (typeof v === ____) {
return v.toUpperCase();
}
return v.toFixed(0);
}
function upper(v: string | number): string {
if (typeof v === "string") {
return v.toUpperCase();
}
return v.toFixed(0);
}
Explanation: For typeof narrowing the value is compared against the possible typeof string "string"; inside the condition v is treated as string.
3 typeof narrowing parts
| Term | Meaning |
|---|---|
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 |