Type Inference & Union Types
TypeScript can infer types automatically. Union types let a variable hold more than one type.
20 min•By Priygop Team•Last updated: Feb 2026
Type Inference & Union Types
TypeScript's type inference means you often don't need to write type annotations — TypeScript figures it out from the value. Union types (using |) allow a variable to be one of several types. For example, string | number means the variable can be either a string or a number.
Key Concepts
- Type inference — TypeScript deduces type from assigned value
- Union types — string | number — can be either type
- Literal types — 'red' | 'green' | 'blue' — only specific values
- typeof guard — check type at runtime: if (typeof x === 'string')
- Avoid any — it disables type checking entirely
- unknown — safer alternative to any
Union Types Example
Example
// Type inference — no annotation needed
let message = "Hello"; // TypeScript infers: string
let count = 42; // TypeScript infers: number
let active = true; // TypeScript infers: boolean
// Union types — can be string OR number
let id: string | number;
id = 101; // OK
id = "user-1"; // Also OK
// Function accepting string or number
function printId(id: string | number): void {
if (typeof id === "string") {
console.log("String ID:", id.toUpperCase());
} else {
console.log("Number ID:", id);
}
}
printId(101);
printId("user-1");
// Literal types — only specific values allowed
type Direction = "north" | "south" | "east" | "west";
let move: Direction = "north"; // OK
// move = "up"; // ERROR: not in the union
// Optional chaining
interface User { name: string; address?: { city: string } }
const user: User = { name: "Alice" };
console.log(user.address?.city ?? "No city"); // "No city"Try It Yourself: Union Types
Try It Yourself: Union TypesJavaScript
JavaScript Editor
✓ ValidTab = 2 spaces
JavaScript|34 lines|934 chars|✓ Valid syntax
UTF-8