Type Guards and Narrowing
Typeof Guard
typeof checks narrow primitive unions before code uses type-specific operations.
Typeof Guard
typeof.ts
function describeValue(value: string | number): string {
if (typeof value === "number") {
return `number=${value * 2}`;
}
return `text=${value.toUpperCase()}`;
}
const useNumber: boolean = ;
const input: string | number = useNumber ? 7 : "ts";
const result: string = describeValue(input);
console.log(result);
function describeValue(value: string | number): string {
if (typeof value === "number") {
return `number=${value * 2}`;
}
return `text=${value.toUpperCase()}`;
}
const useNumber: boolean = ;
const input: string | number = useNumber ? 7 : "ts";
const result: string = describeValue(input);
console.log(result);
typeof guard
`typeof value === "number"` tells TypeScript that the guarded branch has a number.