Narrowing Types
What
Type narrowing is the process of making a type more specific as you write your code. By using conditionals and checks, you can move from a broad type (like a union) to a specific member of that union.
How
TypeScript’s control flow analysis recognizes logical checks (like if statements) and automatically narrows the type within that block:
type Witcher = { type: "witcher"; magic: boolean };
type Human = { type: "human"; age: number };
type Character = Witcher | Human;
function process(char: Character) {
if (char.type === "witcher") {
// TypeScript knows char is a Witcher here
console.log(char.magic);
}
}
Why
Narrower types provide better editor tooling, clearer self-documentation, and ensure that you only access properties that actually exist on a given value. It prevents runtime crashes caused by accessing undefined properties.
Summary
The more specific your types, the safer and more predictable your code becomes.