Lessons in this course (9)

7. Mapped, conditional and template literal types

AdvancedMediumLesson 7 of 9
typescript
// Mapped type: make every property a getter function
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
type CustomerGetters = Getters<{ name: string; age: number }>;   // { getName(): string; getAge(): number }

// Conditional type with infer
type ElementOf<T> = T extends (infer U)[] ? U : never;
type X = ElementOf<string[]>;   // string

// Template literal types
type HttpMethod = "GET" | "POST";
type Route = `/api/${"orders" | "customers"}`;
type Endpoint = `${HttpMethod} ${Route}`;    // "GET /api/orders" | ...

// satisfies: check against a type but keep the precise inferred type
const config = { api: "https://api.example.com", retries: 3 } satisfies Record<string, string | number>;
config.retries.toFixed();   // still known to be number