Typescript Advanced Types

Typescript Advanced Types

Teaches an AI agent TypeScript's advanced type system: generics, conditional and mapped types, template literal types and utility types.

Skill files2 files

references/

SKILL.md319 lines
1
---
2
name: typescript-advanced-types
3
description: 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
8
Comprehensive 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
30
function identity<T>(value: T): T {
31
return value;
32
}
33
34
const num = identity<number>(42); // Type: number
35
const str = identity<string>("hello"); // Type: string
36
const auto = identity(true); // Type inferred: boolean
37
```
38
39
**Generic Constraints:**
40
41
```typescript
42
interface HasLength {
43
length: number;
44
}
45
46
function logLength<T extends HasLength>(item: T): T {
47
console.log(item.length);
48
return item;
49
}
50
51
logLength("hello"); // OK: string has length
52
logLength([1, 2, 3]); // OK: array has length
53
logLength({ length: 10 }); // OK: object has length
54
// logLength(42); // Error: number has no length
55
```
56
57
**Multiple Type Parameters:**
58
59
```typescript
60
function merge<T, U>(obj1: T, obj2: U): T & U {
61
return { ...obj1, ...obj2 };
62
}
63
64
const 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
75
type IsString<T> = T extends string ? true : false;
76
77
type A = IsString<string>; // true
78
type B = IsString<number>; // false
79
```
80
81
**Extracting Return Types:**
82
83
```typescript
84
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
85
86
function getUser() {
87
return { id: 1, name: "John" };
88
}
89
90
type User = ReturnType<typeof getUser>;
91
// Type: { id: number; name: string; }
92
```
93
94
**Distributive Conditional Types:**
95
96
```typescript
97
type ToArray<T> = T extends any ? T[] : never;
98
99
type StrOrNumArray = ToArray<string | number>;
100
// Type: string[] | number[]
101
```
102
103
**Nested Conditions:**
104
105
```typescript
106
type 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
118
type T1 = TypeName<string>; // "string"
119
type 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
129
type Readonly<T> = {
130
readonly [P in keyof T]: T[P];
131
};
132
133
interface User {
134
id: number;
135
name: string;
136
}
137
138
type ReadonlyUser = Readonly<User>;
139
// Type: { readonly id: number; readonly name: string; }
140
```
141
142
**Optional Properties:**
143
144
```typescript
145
type Partial<T> = {
146
[P in keyof T]?: T[P];
147
};
148
149
type PartialUser = Partial<User>;
150
// Type: { id?: number; name?: string; }
151
```
152
153
**Key Remapping:**
154
155
```typescript
156
type Getters<T> = {
157
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
158
};
159
160
interface Person {
161
name: string;
162
age: number;
163
}
164
165
type PersonGetters = Getters<Person>;
166
// Type: { getName: () => string; getAge: () => number; }
167
```
168
169
**Filtering Properties:**
170
171
```typescript
172
type PickByType<T, U> = {
173
[K in keyof T as T[K] extends U ? K : never]: T[K];
174
};
175
176
interface Mixed {
177
id: number;
178
name: string;
179
age: number;
180
active: boolean;
181
}
182
183
type 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
194
type EventName = "click" | "focus" | "blur";
195
type EventHandler = `on${Capitalize<EventName>}`;
196
// Type: "onClick" | "onFocus" | "onBlur"
197
```
198
199
**String Manipulation:**
200
201
```typescript
202
type UppercaseGreeting = Uppercase<"hello">; // "HELLO"
203
type LowercaseGreeting = Lowercase<"HELLO">; // "hello"
204
type CapitalizedName = Capitalize<"john">; // "John"
205
type UncapitalizedName = Uncapitalize<"John">; // "john"
206
```
207
208
**Path Building:**
209
210
```typescript
211
type 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
217
interface Config {
218
server: {
219
host: string;
220
port: number;
221
};
222
database: {
223
url: string;
224
};
225
}
226
227
type 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
237
type PartialUser = Partial<User>;
238
239
// Required<T> - Make all properties required
240
type RequiredUser = Required<PartialUser>;
241
242
// Readonly<T> - Make all properties readonly
243
type ReadonlyUser = Readonly<User>;
244
245
// Pick<T, K> - Select specific properties
246
type UserName = Pick<User, "name" | "email">;
247
248
// Omit<T, K> - Remove specific properties
249
type UserWithoutPassword = Omit<User, "password">;
250
251
// Exclude<T, U> - Exclude types from union
252
type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
253
254
// Extract<T, U> - Extract types from union
255
type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"
256
257
// NonNullable<T> - Exclude null and undefined
258
type T3 = NonNullable<string | null | undefined>; // string
259
260
// Record<K, T> - Create object type with keys K and values T
261
type PageInfo = Record<"home" | "about", { title: string }>;
262
```
263
264
## Detailed worked examples and patterns
265
266
Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient.
267
268
## Best Practices
269
270
1. **Use `unknown` over `any`**: Enforce type checking
271
2. **Prefer `interface` for object shapes**: Better error messages
272
3. **Use `type` for unions and complex types**: More flexible
273
4. **Leverage type inference**: Let TypeScript infer when possible
274
5. **Create helper types**: Build reusable type utilities
275
6. **Use const assertions**: Preserve literal types
276
7. **Avoid type assertions**: Use type guards instead
277
8. **Document complex types**: Add JSDoc comments
278
9. **Use strict mode**: Enable all strict compiler options
279
10. **Test your types**: Use type tests to verify type behavior
280
281
## Type Testing
282
283
```typescript
284
// Type assertion tests
285
type AssertEqual<T, U> = [T] extends [U]
286
? [U] extends [T]
287
? true
288
: false
289
: false;
290
291
type Test1 = AssertEqual<string, string>; // true
292
type Test2 = AssertEqual<string, number>; // false
293
type Test3 = AssertEqual<string | number, string>; // false
294
295
// Expect error helper
296
type ExpectError<T extends never> = T;
297
298
// Example usage
299
type ShouldError = ExpectError<AssertEqual<string, number>>;
300
```
301
302
## Common Pitfalls
303
304
1. **Over-using `any`**: Defeats the purpose of TypeScript
305
2. **Ignoring strict null checks**: Can lead to runtime errors
306
3. **Too complex types**: Can slow down compilation
307
4. **Not using discriminated unions**: Misses type narrowing opportunities
308
5. **Forgetting readonly modifiers**: Allows unintended mutations
309
6. **Circular type references**: Can cause compiler errors
310
7. **Not handling edge cases**: Like empty arrays or null values
311
312
## Performance Considerations
313
314
- Avoid deeply nested conditional types
315
- Use simple types when possible
316
- Cache complex type computations
317
- Limit recursion depth in recursive types
318
- Use build tools to skip type checking in production
319

© Seth Hobson · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…