TypeScript
Beginner
1 min read
Arrays, Tuples, and Union Types
Example
// Array types — two equivalent notations
const nums: number[] = [1, 2, 3];
const strs: Array<string> = ["a", "b", "c"];
// Read-only array
const constants: readonly number[] = [10, 20, 30];
// constants.push(40); // Error
// Tuple — fixed positions with specific types
type RGB = [red: number, green: number, blue: number];
const red: RGB = [255, 0, 0];
const [r, g, b] = red;
// Rest element in tuple
type StringsWithNumber = [string, ...string[], number];
const valid: StringsWithNumber = ["a", "b", "c", 42];
// Union types
type ID = string | number;
function printId(id: ID): void {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id.toFixed(0));
}
}
// Discriminated union
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "rect": return s.width * s.height;
}
}
// Intersection types
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
const alice: Person = { name: "Alice", age: 30 };
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