📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 11

Retour
Alias de type (Type Aliases)
Facile
type ChaineOuNombre = string | number;
let maValeur: ChaineOuNombre;
Gardes de type (Type Guards)
Intermédiaire
function afficher(valeur: string | number) {
    if (typeof valeur === "string") {
        console.log(valeur.toUpperCase());
    }
}
Type d'intersection (Intersection Types)
Intermédiaire
interface A { a(): void }
interface B { b(): void }

let x: A & B;
Type d'union (Union Types)
Facile
let valeur: string | number;
valeur = "Bonjour";
valeur = 123;
Types conditionnels
Avancé
type TypeNom<T> = T extends string ? "string" : "autre";
Types littéraux
Intermédiaire
let direction: "gauche" | "droite" | "haut" | "bas";
Types mappés (Mapped Types)
Avancé
type ReadonlyProps<T> = { readonly [P in keyof T]: T[P]; };
Types utilitaires : Omit<T, K>
Avancé
type TodoSansDescription = Omit<Todo, "description">;
Types utilitaires : Partial<T>
Avancé
interface Todo { title: string; description: string; }

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}
Types utilitaires : Pick<T, K>
Avancé
type TodoPreview = Pick<Todo, "title">;
Types utilitaires : Readonly<T>
Avancé
const todo: Readonly<Todo> = { title: "...", description: "..." };
// todo.title = "hello"; // Erreur