📘
Advanced Types: Literal, Tuple, and More
Intermediate
100 XP
40 min
Lesson Content
Advanced Types in TypeScript
TypeScript offers powerful type features that make your code more precise and type-safe.
Literal Types
// Specific string values
let status: "pending" | "approved" | "rejected";
// Specific number values
let dice: 1 | 2 | 3 | 4 | 5 | 6;Tuple Types
// Fixed-length array with specific types
let coordinates: [number, number] = [10, 20];
let person: [string, number, boolean] = ["John", 30, true];Type Aliases
type ID = string | number;
type Status = "active" | "inactive";
type User = {
id: ID;
status: Status;
};Example Code
Use literal types and tuples
type Status = "loading" | "success" | "error";
function handleStatus(status: Status): string {
return `Status: ${status}`;
}
let point: [number, number] = [10, 20];
console.log(`Point: (${point[0]}, ${point[1]})`);
console.log(handleStatus("success"));Expected Output:
Point: (10, 20) Status: success
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code