IntermediateLesson 9 of 15
Utility Types – TypeScript
Partial, Pick, Omit, Record & co. – deriving types from types.
TypeScript ships built-in helper types that turn existing types into new ones – so you maintain a type definition only once.
interface Produkt {
id: number;
name: string;
preis: number;
lager: number;
}
type Entwurf = Partial<Produkt>; // everything optional
type Pflicht = Required<Produkt>; // everything required
type Fest = Readonly<Produkt>; // everything read-only
type Vorschau = Pick<Produkt, "name" | "preis">; // only these fields
type OhneId = Omit<Produkt, "id">; // all except idA practical example: an update function that changes only some of the fields and never the id:
type ProduktUpdate = Partial<Omit<Produkt, "id">>;
function aktualisiere(p: Produkt, u: ProduktUpdate): Produkt {
return { ...p, ...u };
}
const kaffee: Produkt = { id: 1, name: "Coffee", preis: 4.5, lager: 20 };
console.log(aktualisiere(kaffee, { preis: 4.99 }));
// aktualisiere(kaffee, { id: 2 }); // Error: 'id' does not exist in the update typeRecord<K, V> builds dictionaries with fixed keys. Exclude, Extract and NonNullable process unions. ReturnType, Parameters and Awaited extract types from functions:
type Rolle = "admin" | "editor" | "gast";
const rechte: Record<Rolle, string[]> = {
admin: ["read", "write", "delete"],
editor: ["read", "write"],
gast: ["read"]
};
type OhneGast = Exclude<Rolle, "gast">; // "admin" | "editor"
type NurText = Extract<string | number, string>; // string
type Sicher = NonNullable<string | null>; // string
type R = ReturnType<typeof aktualisiere>; // Produkt
type P = Parameters<typeof aktualisiere>; // [p: Produkt, u: ProduktUpdate]
type Ergebnis = Awaited<Promise<string>>; // stringTipA
Record<Rolle, ...> forces you to provide an entry for every role – if you forget the entry for a new role, the compiler reports it immediately.