Interfaces and Advanced Types
Structure your data with interfaces
10-15 min
Interfaces and Advanced Types
Interfaces and custom types are at the heart of TypeScript. They let you define the shape of your data and create clear contracts in your code.
Basic Interfaces
Defining an Interface
interface Utilisateur {
id: number;
nom: string;
email: string;
age: number;
}
// Usage
let utilisateur: Utilisateur = {
id: 1,
nom: "Alice",
email: "alice@example.com",
age: 30
};
Optional Properties
interface Produit {
id: number;
nom: string;
prix: number;
description?: string; // Optional property
enStock?: boolean;
}
let produit1: Produit = {
id: 1,
nom: "Ordinateur",
prix: 999
// description and enStock are optional
};
let produit2: Produit = {
id: 2,
nom: "Souris",
prix: 25,
description: "Souris ergonomique",
enStock: true
};
Read-Only Properties
interface Configuration {
readonly apiUrl: string;
readonly version: string;
timeout: number;
}
let config: Configuration = {
apiUrl: "https://api.example.com",
version: "1.0.0",
timeout: 5000
};
// config.apiUrl = "nouvelle-url"; // ❌ Error: read-only property
config.timeout = 10000; // ✅ OK
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion