TypeScript
Beginner
1 min read
Literal Types and Type Narrowing
Example
// Literal types
type Direction = "north" | "south" | "east" | "west";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
type Done = true; // only the value true
function move(dir: Direction, steps: number): string {
return `Move ${steps} steps ${dir}`;
}
// Literal type inference — use 'as const' to preserve literals
const config = {
endpoint: "https://api.example.com",
retries: 3,
} as const;
// config.retries is 3, not number
// Narrowing with typeof
function format(value: string | number): string {
if (typeof value === "string") {
return value.trim(); // string here
}
return value.toFixed(2); // number here
}
// Narrowing with 'in'
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function makeSound(animal: Cat | Dog): void {
if ("meow" in animal) {
animal.meow();
} else {
animal.bark();
}
}
// satisfies — validate type, keep narrow inference
const palette = {
red: [255, 0, 0],
green: "#00ff00",
} satisfies Record<string, string | number[]>;
// palette.red is number[], not string | number[]
const first = palette.red[0]; // number
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript