TypeScript — Type Aliases
Type guards
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function process(value: string | number) {
if (isString(value)) {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
Discriminated unions
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
}
}
Exhaustive checking
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
function processShape(shape: Shape) {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
default: return assertNever(shape);
}
}
Mini Practice
Write TypeScript code that:
- Creates a type guard function
- Uses discriminated unions
- Demonstrates exhaustive checking
- Narrows types with typeof and instanceof
Up Next
In the next lesson, you'll learn about Error Handling — Result types and error patterns.
Related Topics
Frequently Asked Questions about Type Aliases
What is Type Aliases in TypeScript?
Type Aliases is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Type Aliases?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Type Aliases.
Why is Type Aliases important in TypeScript?
Type Aliases is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.