Skills · Coding

Typescript Advanced Types

Unverified31/40

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.

Originally by wshobson · MIT

Claude CodePartialHas SKILL.md but declares no allowed-tools — Claude Code will ask for permission each time
CursorPartialPlain prose you can paste in — but no Cursor rules file
CodexPartialPlain prose you can paste in — but no AGENTS.md
Gemini CLIPartialPlain prose you can paste in
CopilotPartialPlain prose you can paste in — but no Copilot instructions file
npx agentalley add typescript-advanced-types

This command does not work yet — the CLI is still being built. Until then, use Raw in the reader below to take the file.

Who is stuck, and on what

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.

The whole source

No sign-in, no blur, nothing truncated
typescript-advanced-types/SKILL.md319 lines7.8 KBRawView on GitHub
Frontmatter — 2 properties
nametypescript-advanced-types
descriptionMaster 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.
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---A5No allowed-tools declared — no way to tell what this skill may touch
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## Detailed worked examples and patterns
265 
266Detailed 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 
2701. **Use `unknown` over `any`**: Enforce type checking
2712. **Prefer `interface` for object shapes**: Better error messages
2723. **Use `type` for unions and complex types**: More flexible
2734. **Leverage type inference**: Let TypeScript infer when possible
2745. **Create helper types**: Build reusable type utilities
2756. **Use const assertions**: Preserve literal types
2767. **Avoid type assertions**: Use type guards instead
2778. **Document complex types**: Add JSDoc comments
2789. **Use strict mode**: Enable all strict compiler options
27910. **Test your types**: Use type tests to verify type behavior
280 
281## Type Testing
282 
283```typescript
284// Type assertion tests
285type AssertEqual<T, U> = [T] extends [U]
286 ? [U] extends [T]
287 ? true
288 : false
289 : false;
290 
291type Test1 = AssertEqual<string, string>; // true
292type Test2 = AssertEqual<string, number>; // false
293type Test3 = AssertEqual<string | number, string>; // false
294 
295// Expect error helper
296type ExpectError<T extends never> = T;
297 
298// Example usage
299type ShouldError = ExpectError<AssertEqual<string, number>>;
300```
301 
302## Common Pitfalls
303 
3041. **Over-using `any`**: Defeats the purpose of TypeScript
3052. **Ignoring strict null checks**: Can lead to runtime errors
3063. **Too complex types**: Can slow down compilation
3074. **Not using discriminated unions**: Misses type narrowing opportunities
3085. **Forgetting readonly modifiers**: Allows unintended mutations
3096. **Circular type references**: Can cause compiler errors
3107. **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 

Reviews

Installed this one?Write the first review and take the Trailblazer badge.

Reviews only open after a real install, so this is empty — and we leave it empty rather than invent one.

Alternatives

Also in Coding