T
Types Avancés
TypeScript Syntax Guide
Union, Intersection, Alias de Types et Types Littéraux
Types Avancés
Union, Intersection, Alias de Types et Types Littéraux
TypeScript types avancés (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 offre des fonctionnalités de type avancées comme les types Union (une valeur peut être l'un de plusieurs types), les types Intersection (combinaison de plusieurs types en un), les alias de types (donner un nouveau nom à un type) et les types littéraux (restriction d'une variable à des valeurs spécifiques de chaîne, nombre ou booléen).
Common Use Cases
- Créer des paramètres de fonction flexibles
- Combiner des interfaces
- Définir des noms de type personnalisés pour des types complexes
- Appliquer des valeurs spécifiques aux variables
Related TypeScript Syntax
Master Types Avancés in TypeScript
Understanding Types Avancés 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 Types Avancés effectively in your TypeScript projects.
Key Takeaways
- Créer des paramètres de fonction flexibles
- Combiner des interfaces
- Définir des noms de type personnalisés pour des types complexes