T
Advanced Types
TypeScript syntax guide
Union, Intersection, Type Aliases, and Literal Types
Advanced Types
Union, Intersection, Type Aliases, and Literal Types
TypeScript advanced types (typescript)
// Union types
type StringOrNumber = string | number;
function formatValue(value: StringOrNumber): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}
// Discriminated unions
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
interface Circle {
kind: "circle";
radius: number;
}
type Shape = Square | Rectangle | Circle;
function getArea(shape: Shape): number {
switch (shape.kind) {
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
case "circle":
return Math.PI * shape.radius ** 2;
}
}
// Intersection types
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age; // Must have both name and age
const person: Person = {
name: "John",
age: 25
};
// Type guards
function isString(value: unknown): value is string {
return typeof value === "string";
}
function isShape(obj: any): obj is Shape {
return obj && typeof obj.kind === "string";
}
// Using type guards
function processValue(value: unknown): string {
if (isString(value)) {
return value.toUpperCase(); // TypeScript knows value is string
}
return "Not a string";
}
// keyof operator
type PersonKeys = keyof Person; // "name" | "age"
// Indexed access types
type PersonName = Person["name"]; // string
// typeof operator for types
const config = {
apiUrl: "https://api.example.com",
timeout: 5000
};
type Config = typeof config;
// Mapped types with template literals
type EventHandlers<T extends string> = {
[K in T as `on${Capitalize<K>}`]: () => void;
};
type ButtonEvents = EventHandlers<'click' | 'hover'>;
// Results in: { onClick: () => void; onHover: () => void; }
// Never type
function throwError(message: string): never {
throw new Error(message);
}
// Exhaustive checking with never
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
function handleShape(shape: Shape) {
switch (shape.kind) {
case "square":
return shape.size;
case "rectangle":
return shape.width;
case "circle":
return shape.radius;
default:
return assertNever(shape); // Ensures all cases are handled
}
}
Explanation
TypeScript offers advanced type features like Union Types (a value can be one of several types), Intersection Types (combining multiple types into one), Type Aliases (giving a new name to a type), and Literal Types (restricting a variable to specific string, number, or boolean values).
Common Use Cases
- Creating flexible function parameters
- Combining interfaces
- Defining custom type names for complex types
- Enforcing specific values for variables
Related TypeScript Syntax
Master Advanced Types in TypeScript
Understanding advanced types is fundamental to writing clean and efficient TypeScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using advanced types effectively in your TypeScript projects.
Key Takeaways
- Creating flexible function parameters
- Combining interfaces
- Defining custom type names for complex types