5 min read
•Question 28 of 48mediumWhat is Type Narrowing in TypeScript?
Refining types through control flow.
What You'll Learn
- How narrowing works
- Different narrowing techniques
- Custom type predicates
What is Type Narrowing?
TypeScript analyzes code flow to refine types within blocks.
code.tsTypeScript
function print(value: string | number) {
// value is string | number here
if (typeof value === "string") {
// value is string here
console.log(value.toUpperCase());
} else {
// value is number here
console.log(value.toFixed(2));
}
}Narrowing Techniques
code.tsTypeScript
// typeof
if (typeof x === "string") { }
// instanceof
if (x instanceof Date) { }
// in operator
if ("name" in obj) { }
// Truthiness
if (value) { } // excludes null, undefined, 0, "", etc.
// Equality
if (x === null) { }
// Discriminated unions
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function area(shape: Shape) {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
} else {
return shape.side ** 2;
}
}Type Predicates
code.tsTypeScript
function isString(value: unknown): value is string {
return typeof value === "string";
}
if (isString(value)) {
// value is string here
}