xonecas.io
556
Bn

bees-nest / files

bees-nest / .opencode / skills / typescript-advanced-types / SKILL.md

16.7 KB
1---
2name: typescript-advanced-types
3description: Master TypeScript's advanced type system including generics, conditional types, mapped types, template literals, and utility types for building type-safe applications. Use when implementing complex type logic, creating reusable type utilities, or ensuring compile-time type safety in TypeScript projects.
4---
5
6# TypeScript Advanced Types
7
8Comprehensive guidance for mastering TypeScript's advanced type system including generics, conditional types, mapped types, template literal types, and utility types for building robust, type-safe applications.
9
10## When to Use This Skill
11
12- Building type-safe libraries or frameworks
13- Creating reusable generic components
14- Implementing complex type inference logic
15- Designing type-safe API clients
16- Building form validation systems
17- Creating strongly-typed configuration objects
18- Implementing type-safe state management
19- Migrating JavaScript codebases to TypeScript
20
21## Core Concepts
22
23### 1. Generics
24
25**Purpose:** Create reusable, type-flexible components while maintaining type safety.
26
27**Basic Generic Function:**
28
29```typescript
30function identity<T>(value: T): T {
31  return value;
32}
33
34const num = identity<number>(42); // Type: number
35const str = identity<string>("hello"); // Type: string
36const auto = identity(true); // Type inferred: boolean
37```
38
39**Generic Constraints:**
40
41```typescript
42interface HasLength {
43  length: number;
44}
45
46function logLength<T extends HasLength>(item: T): T {
47  console.log(item.length);
48  return item;
49}
50
51logLength("hello"); // OK: string has length
52logLength([1, 2, 3]); // OK: array has length
53logLength({ length: 10 }); // OK: object has length
54// logLength(42);             // Error: number has no length
55```
56
57**Multiple Type Parameters:**
58
59```typescript
60function merge<T, U>(obj1: T, obj2: U): T & U {
61  return { ...obj1, ...obj2 };
62}
63
64const merged = merge({ name: "John" }, { age: 30 });
65// Type: { name: string } & { age: number }
66```
67
68### 2. Conditional Types
69
70**Purpose:** Create types that depend on conditions, enabling sophisticated type logic.
71
72**Basic Conditional Type:**
73
74```typescript
75type IsString<T> = T extends string ? true : false;
76
77type A = IsString<string>; // true
78type B = IsString<number>; // false
79```
80
81**Extracting Return Types:**
82
83```typescript
84type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
85
86function getUser() {
87  return { id: 1, name: "John" };
88}
89
90type User = ReturnType<typeof getUser>;
91// Type: { id: number; name: string; }
92```
93
94**Distributive Conditional Types:**
95
96```typescript
97type ToArray<T> = T extends any ? T[] : never;
98
99type StrOrNumArray = ToArray<string | number>;
100// Type: string[] | number[]
101```
102
103**Nested Conditions:**
104
105```typescript
106type TypeName<T> = T extends string
107  ? "string"
108  : T extends number
109    ? "number"
110    : T extends boolean
111      ? "boolean"
112      : T extends undefined
113        ? "undefined"
114        : T extends Function
115          ? "function"
116          : "object";
117
118type T1 = TypeName<string>; // "string"
119type T2 = TypeName<() => void>; // "function"
120```
121
122### 3. Mapped Types
123
124**Purpose:** Transform existing types by iterating over their properties.
125
126**Basic Mapped Type:**
127
128```typescript
129type Readonly<T> = {
130  readonly [P in keyof T]: T[P];
131};
132
133interface User {
134  id: number;
135  name: string;
136}
137
138type ReadonlyUser = Readonly<User>;
139// Type: { readonly id: number; readonly name: string; }
140```
141
142**Optional Properties:**
143
144```typescript
145type Partial<T> = {
146  [P in keyof T]?: T[P];
147};
148
149type PartialUser = Partial<User>;
150// Type: { id?: number; name?: string; }
151```
152
153**Key Remapping:**
154
155```typescript
156type Getters<T> = {
157  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
158};
159
160interface Person {
161  name: string;
162  age: number;
163}
164
165type PersonGetters = Getters<Person>;
166// Type: { getName: () => string; getAge: () => number; }
167```
168
169**Filtering Properties:**
170
171```typescript
172type PickByType<T, U> = {
173  [K in keyof T as T[K] extends U ? K : never]: T[K];
174};
175
176interface Mixed {
177  id: number;
178  name: string;
179  age: number;
180  active: boolean;
181}
182
183type OnlyNumbers = PickByType<Mixed, number>;
184// Type: { id: number; age: number; }
185```
186
187### 4. Template Literal Types
188
189**Purpose:** Create string-based types with pattern matching and transformation.
190
191**Basic Template Literal:**
192
193```typescript
194type EventName = "click" | "focus" | "blur";
195type EventHandler = `on${Capitalize<EventName>}`;
196// Type: "onClick" | "onFocus" | "onBlur"
197```
198
199**String Manipulation:**
200
201```typescript
202type UppercaseGreeting = Uppercase<"hello">; // "HELLO"
203type LowercaseGreeting = Lowercase<"HELLO">; // "hello"
204type CapitalizedName = Capitalize<"john">; // "John"
205type UncapitalizedName = Uncapitalize<"John">; // "john"
206```
207
208**Path Building:**
209
210```typescript
211type Path<T> = T extends object
212  ? {
213      [K in keyof T]: K extends string ? `${K}` | `${K}.${Path<T[K]>}` : never;
214    }[keyof T]
215  : never;
216
217interface Config {
218  server: {
219    host: string;
220    port: number;
221  };
222  database: {
223    url: string;
224  };
225}
226
227type ConfigPath = Path<Config>;
228// Type: "server" | "database" | "server.host" | "server.port" | "database.url"
229```
230
231### 5. Utility Types
232
233**Built-in Utility Types:**
234
235```typescript
236// Partial<T> - Make all properties optional
237type PartialUser = Partial<User>;
238
239// Required<T> - Make all properties required
240type RequiredUser = Required<PartialUser>;
241
242// Readonly<T> - Make all properties readonly
243type ReadonlyUser = Readonly<User>;
244
245// Pick<T, K> - Select specific properties
246type UserName = Pick<User, "name" | "email">;
247
248// Omit<T, K> - Remove specific properties
249type UserWithoutPassword = Omit<User, "password">;
250
251// Exclude<T, U> - Exclude types from union
252type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
253
254// Extract<T, U> - Extract types from union
255type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"
256
257// NonNullable<T> - Exclude null and undefined
258type T3 = NonNullable<string | null | undefined>; // string
259
260// Record<K, T> - Create object type with keys K and values T
261type PageInfo = Record<"home" | "about", { title: string }>;
262```
263
264## Advanced Patterns
265
266### Pattern 1: Type-Safe Event Emitter
267
268```typescript
269type EventMap = {
270  "user:created": { id: string; name: string };
271  "user:updated": { id: string };
272  "user:deleted": { id: string };
273};
274
275class TypedEventEmitter<T extends Record<string, any>> {
276  private listeners: {
277    [K in keyof T]?: Array<(data: T[K]) => void>;
278  } = {};
279
280  on<K extends keyof T>(event: K, callback: (data: T[K]) => void): void {
281    if (!this.listeners[event]) {
282      this.listeners[event] = [];
283    }
284    this.listeners[event]!.push(callback);
285  }
286
287  emit<K extends keyof T>(event: K, data: T[K]): void {
288    const callbacks = this.listeners[event];
289    if (callbacks) {
290      callbacks.forEach((callback) => callback(data));
291    }
292  }
293}
294
295const emitter = new TypedEventEmitter<EventMap>();
296
297emitter.on("user:created", (data) => {
298  console.log(data.id, data.name); // Type-safe!
299});
300
301emitter.emit("user:created", { id: "1", name: "John" });
302// emitter.emit("user:created", { id: "1" });  // Error: missing 'name'
303```
304
305### Pattern 2: Type-Safe API Client
306
307```typescript
308type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";
309
310type EndpointConfig = {
311  "/users": {
312    GET: { response: User[] };
313    POST: { body: { name: string; email: string }; response: User };
314  };
315  "/users/:id": {
316    GET: { params: { id: string }; response: User };
317    PUT: { params: { id: string }; body: Partial<User>; response: User };
318    DELETE: { params: { id: string }; response: void };
319  };
320};
321
322type ExtractParams<T> = T extends { params: infer P } ? P : never;
323type ExtractBody<T> = T extends { body: infer B } ? B : never;
324type ExtractResponse<T> = T extends { response: infer R } ? R : never;
325
326class APIClient<Config extends Record<string, Record<HTTPMethod, any>>> {
327  async request<Path extends keyof Config, Method extends keyof Config[Path]>(
328    path: Path,
329    method: Method,
330    ...[options]: ExtractParams<Config[Path][Method]> extends never
331      ? ExtractBody<Config[Path][Method]> extends never
332        ? []
333        : [{ body: ExtractBody<Config[Path][Method]> }]
334      : [
335          {
336            params: ExtractParams<Config[Path][Method]>;
337            body?: ExtractBody<Config[Path][Method]>;
338          },
339        ]
340  ): Promise<ExtractResponse<Config[Path][Method]>> {
341    // Implementation here
342    return {} as any;
343  }
344}
345
346const api = new APIClient<EndpointConfig>();
347
348// Type-safe API calls
349const users = await api.request("/users", "GET");
350// Type: User[]
351
352const newUser = await api.request("/users", "POST", {
353  body: { name: "John", email: "john@example.com" },
354});
355// Type: User
356
357const user = await api.request("/users/:id", "GET", {
358  params: { id: "123" },
359});
360// Type: User
361```
362
363### Pattern 3: Builder Pattern with Type Safety
364
365```typescript
366type BuilderState<T> = {
367  [K in keyof T]: T[K] | undefined;
368};
369
370type RequiredKeys<T> = {
371  [K in keyof T]-?: {} extends Pick<T, K> ? never : K;
372}[keyof T];
373
374type OptionalKeys<T> = {
375  [K in keyof T]-?: {} extends Pick<T, K> ? K : never;
376}[keyof T];
377
378type IsComplete<T, S> =
379  RequiredKeys<T> extends keyof S
380    ? S[RequiredKeys<T>] extends undefined
381      ? false
382      : true
383    : false;
384
385class Builder<T, S extends BuilderState<T> = {}> {
386  private state: S = {} as S;
387
388  set<K extends keyof T>(key: K, value: T[K]): Builder<T, S & Record<K, T[K]>> {
389    this.state[key] = value;
390    return this as any;
391  }
392
393  build(this: IsComplete<T, S> extends true ? this : never): T {
394    return this.state as T;
395  }
396}
397
398interface User {
399  id: string;
400  name: string;
401  email: string;
402  age?: number;
403}
404
405const builder = new Builder<User>();
406
407const user = builder
408  .set("id", "1")
409  .set("name", "John")
410  .set("email", "john@example.com")
411  .build(); // OK: all required fields set
412
413// const incomplete = builder
414//   .set("id", "1")
415//   .build();  // Error: missing required fields
416```
417
418### Pattern 4: Deep Readonly/Partial
419
420```typescript
421type DeepReadonly<T> = {
422  readonly [P in keyof T]: T[P] extends object
423    ? T[P] extends Function
424      ? T[P]
425      : DeepReadonly<T[P]>
426    : T[P];
427};
428
429type DeepPartial<T> = {
430  [P in keyof T]?: T[P] extends object
431    ? T[P] extends Array<infer U>
432      ? Array<DeepPartial<U>>
433      : DeepPartial<T[P]>
434    : T[P];
435};
436
437interface Config {
438  server: {
439    host: string;
440    port: number;
441    ssl: {
442      enabled: boolean;
443      cert: string;
444    };
445  };
446  database: {
447    url: string;
448    pool: {
449      min: number;
450      max: number;
451    };
452  };
453}
454
455type ReadonlyConfig = DeepReadonly<Config>;
456// All nested properties are readonly
457
458type PartialConfig = DeepPartial<Config>;
459// All nested properties are optional
460```
461
462### Pattern 5: Type-Safe Form Validation
463
464```typescript
465type ValidationRule<T> = {
466  validate: (value: T) => boolean;
467  message: string;
468};
469
470type FieldValidation<T> = {
471  [K in keyof T]?: ValidationRule<T[K]>[];
472};
473
474type ValidationErrors<T> = {
475  [K in keyof T]?: string[];
476};
477
478class FormValidator<T extends Record<string, any>> {
479  constructor(private rules: FieldValidation<T>) {}
480
481  validate(data: T): ValidationErrors<T> | null {
482    const errors: ValidationErrors<T> = {};
483    let hasErrors = false;
484
485    for (const key in this.rules) {
486      const fieldRules = this.rules[key];
487      const value = data[key];
488
489      if (fieldRules) {
490        const fieldErrors: string[] = [];
491
492        for (const rule of fieldRules) {
493          if (!rule.validate(value)) {
494            fieldErrors.push(rule.message);
495          }
496        }
497
498        if (fieldErrors.length > 0) {
499          errors[key] = fieldErrors;
500          hasErrors = true;
501        }
502      }
503    }
504
505    return hasErrors ? errors : null;
506  }
507}
508
509interface LoginForm {
510  email: string;
511  password: string;
512}
513
514const validator = new FormValidator<LoginForm>({
515  email: [
516    {
517      validate: (v) => v.includes("@"),
518      message: "Email must contain @",
519    },
520    {
521      validate: (v) => v.length > 0,
522      message: "Email is required",
523    },
524  ],
525  password: [
526    {
527      validate: (v) => v.length >= 8,
528      message: "Password must be at least 8 characters",
529    },
530  ],
531});
532
533const errors = validator.validate({
534  email: "invalid",
535  password: "short",
536});
537// Type: { email?: string[]; password?: string[]; } | null
538```
539
540### Pattern 6: Discriminated Unions
541
542```typescript
543type Success<T> = {
544  status: "success";
545  data: T;
546};
547
548type Error = {
549  status: "error";
550  error: string;
551};
552
553type Loading = {
554  status: "loading";
555};
556
557type AsyncState<T> = Success<T> | Error | Loading;
558
559function handleState<T>(state: AsyncState<T>): void {
560  switch (state.status) {
561    case "success":
562      console.log(state.data); // Type: T
563      break;
564    case "error":
565      console.log(state.error); // Type: string
566      break;
567    case "loading":
568      console.log("Loading...");
569      break;
570  }
571}
572
573// Type-safe state machine
574type State =
575  | { type: "idle" }
576  | { type: "fetching"; requestId: string }
577  | { type: "success"; data: any }
578  | { type: "error"; error: Error };
579
580type Event =
581  | { type: "FETCH"; requestId: string }
582  | { type: "SUCCESS"; data: any }
583  | { type: "ERROR"; error: Error }
584  | { type: "RESET" };
585
586function reducer(state: State, event: Event): State {
587  switch (state.type) {
588    case "idle":
589      return event.type === "FETCH"
590        ? { type: "fetching", requestId: event.requestId }
591        : state;
592    case "fetching":
593      if (event.type === "SUCCESS") {
594        return { type: "success", data: event.data };
595      }
596      if (event.type === "ERROR") {
597        return { type: "error", error: event.error };
598      }
599      return state;
600    case "success":
601    case "error":
602      return event.type === "RESET" ? { type: "idle" } : state;
603  }
604}
605```
606
607## Type Inference Techniques
608
609### 1. Infer Keyword
610
611```typescript
612// Extract array element type
613type ElementType<T> = T extends (infer U)[] ? U : never;
614
615type NumArray = number[];
616type Num = ElementType<NumArray>; // number
617
618// Extract promise type
619type PromiseType<T> = T extends Promise<infer U> ? U : never;
620
621type AsyncNum = PromiseType<Promise<number>>; // number
622
623// Extract function parameters
624type Parameters<T> = T extends (...args: infer P) => any ? P : never;
625
626function foo(a: string, b: number) {}
627type FooParams = Parameters<typeof foo>; // [string, number]
628```
629
630### 2. Type Guards
631
632```typescript
633function isString(value: unknown): value is string {
634  return typeof value === "string";
635}
636
637function isArrayOf<T>(
638  value: unknown,
639  guard: (item: unknown) => item is T,
640): value is T[] {
641  return Array.isArray(value) && value.every(guard);
642}
643
644const data: unknown = ["a", "b", "c"];
645
646if (isArrayOf(data, isString)) {
647  data.forEach((s) => s.toUpperCase()); // Type: string[]
648}
649```
650
651### 3. Assertion Functions
652
653```typescript
654function assertIsString(value: unknown): asserts value is string {
655  if (typeof value !== "string") {
656    throw new Error("Not a string");
657  }
658}
659
660function processValue(value: unknown) {
661  assertIsString(value);
662  // value is now typed as string
663  console.log(value.toUpperCase());
664}
665```
666
667## Best Practices
668
6691. **Use `unknown` over `any`**: Enforce type checking
6702. **Prefer `interface` for object shapes**: Better error messages
6713. **Use `type` for unions and complex types**: More flexible
6724. **Leverage type inference**: Let TypeScript infer when possible
6735. **Create helper types**: Build reusable type utilities
6746. **Use const assertions**: Preserve literal types
6757. **Avoid type assertions**: Use type guards instead
6768. **Document complex types**: Add JSDoc comments
6779. **Use strict mode**: Enable all strict compiler options
67810. **Test your types**: Use type tests to verify type behavior
679
680## Type Testing
681
682```typescript
683// Type assertion tests
684type AssertEqual<T, U> = [T] extends [U]
685  ? [U] extends [T]
686    ? true
687    : false
688  : false;
689
690type Test1 = AssertEqual<string, string>; // true
691type Test2 = AssertEqual<string, number>; // false
692type Test3 = AssertEqual<string | number, string>; // false
693
694// Expect error helper
695type ExpectError<T extends never> = T;
696
697// Example usage
698type ShouldError = ExpectError<AssertEqual<string, number>>;
699```
700
701## Common Pitfalls
702
7031. **Over-using `any`**: Defeats the purpose of TypeScript
7042. **Ignoring strict null checks**: Can lead to runtime errors
7053. **Too complex types**: Can slow down compilation
7064. **Not using discriminated unions**: Misses type narrowing opportunities
7075. **Forgetting readonly modifiers**: Allows unintended mutations
7086. **Circular type references**: Can cause compiler errors
7097. **Not handling edge cases**: Like empty arrays or null values
710
711## Performance Considerations
712
713- Avoid deeply nested conditional types
714- Use simple types when possible
715- Cache complex type computations
716- Limit recursion depth in recursive types
717- Use build tools to skip type checking in production
718
719## Resources
720
721- **TypeScript Handbook**: https://www.typescriptlang.org/docs/handbook/
722- **Type Challenges**: https://github.com/type-challenges/type-challenges
723- **TypeScript Deep Dive**: https://basarat.gitbook.io/typescript/
724- **Effective TypeScript**: Book by Dan Vanderkam