U

Union Types

Union types allow a value to be one of several types, enabling flexible yet type-safe code.

Code

typescript
1// Basic union type
2type StringOrNumber = string | number;
3
4function formatValue(value: StringOrNumber): string {
5 if (typeof value === "string") {
6 return value.toUpperCase();
7 }
8 return value.toFixed(2);
9}
10
11console.log(formatValue("hello")); // HELLO
12console.log(formatValue(42.567)); // 42.57
13
14// Union with literals (discriminated unions)
15type Status = "pending" | "success" | "error";
16
17interface ApiResponse {
18 status: Status;
19 data?: unknown;
20 error?: string;
21}
22
23function handleResponse(response: ApiResponse): void {
24 switch (response.status) {
25 case "pending":
26 console.log("Loading...");
27 break;
28 case "success":
29 console.log("Data:", response.data);
30 break;
31 case "error":
32 console.log("Error:", response.error);
33 break;
34 }
35}
36
37// Discriminated union with type guards
38type Shape =
39 | { kind: "circle"; radius: number }
40 | { kind: "rectangle"; width: number; height: number }
41 | { kind: "square"; size: number };
42
43function calculateArea(shape: Shape): number {
44 switch (shape.kind) {
45 case "circle":
46 return Math.PI * shape.radius ** 2;
47 case "rectangle":
48 return shape.width * shape.height;
49 case "square":
50 return shape.size ** 2;
51 }
52}
53
54const circle: Shape = { kind: "circle", radius: 5 };
55const rect: Shape = { kind: "rectangle", width: 4, height: 6 };
56
57console.log(`Circle area: ${calculateArea(circle).toFixed(2)}`);
58console.log(`Rectangle area: ${calculateArea(rect)}`);

Run this example locally

$ npx ts-node types/unions.ts