Master TypeScript's advanced type system including generics

Typescript advanced types

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Typescript advanced types cover

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…

---
name: typescript-advanced-types
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.
---

# TypeScript Advanced Types

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.

## When to Use This Skill

- Building type-safe libraries or frameworks
- Creating reusable generic components
- Implementing complex type inference logic
- Designing type-safe API clients
- Building form validation systems
- Creating strongly-typed configuration objects
- Implementing type-safe state management

Overview

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.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill typescript-advanced-types -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/javascript-typescript/skills/typescript-advanced-types
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/4cf80e92696a7414cd01/typescript-advanced-types.zip" -OutFile "$env:TEMP\typescript-advanced-types.zip"; Expand-Archive "$env:TEMP\typescript-advanced-types.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md7.8 KB
  • references/1 file · 8.8 KB
Read the files here
wshobson/4236bb92 files
SKILL.md
Show the full text319 lines

TypeScript Advanced Types

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.

When to Use This Skill

  • Building type-safe libraries or frameworks
  • Creating reusable generic components
  • Implementing complex type inference logic
  • Designing type-safe API clients
  • Building form validation systems
  • Creating strongly-typed configuration objects
  • Implementing type-safe state management
  • Migrating JavaScript codebases to TypeScript

Core Concepts

1. Generics

Purpose: Create reusable, type-flexible components while maintaining type safety.

Basic Generic Function:

function identity<T>(value: T): T {
  return value;
}

const num = identity<number>(42); // Type: number
const str = identity<string>("hello"); // Type: string
const auto = identity(true); // Type inferred: boolean

Generic Constraints:

interface HasLength {
  length: number;
}

function logLength<T extends HasLength>(item: T): T {
  console.log(item.length);
  return item;
}

logLength("hello"); // OK: string has length
logLength([1, 2, 3]); // OK: array has length
logLength({ length: 10 }); // OK: object has length
// logLength(42);             // Error: number has no length

Multiple Type Parameters:

function merge<T, U>(obj1: T, obj2: U): T & U {
  return { ...obj1, ...obj2 };
}

const merged = merge({ name: "John" }, { age: 30 });
// Type: { name: string } & { age: number }
2. Conditional Types

Purpose: Create types that depend on conditions, enabling sophisticated type logic.

Basic Conditional Type:

type IsString<T> = T extends string ? true : false;

type A = IsString<string>; // true
type B = IsString<number>; // false

Extracting Return Types:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

function getUser() {
  return { id: 1, name: "John" };
}

type User = ReturnType<typeof getUser>;
// Type: { id: number; name: string; }

Distributive Conditional Types:

type ToArray<T> = T extends any ? T[] : never;

type StrOrNumArray = ToArray<string | number>;
// Type: string[] | number[]

Nested Conditions:

type TypeName<T> = T extends string
  ? "string"
  : T extends number
    ? "number"
    : T extends boolean
      ? "boolean"
      : T extends undefined
        ? "undefined"
        : T extends Function
          ? "function"
          : "object";

type T1 = TypeName<string>; // "string"
type T2 = TypeName<() => void>; // "function"
3. Mapped Types

Purpose: Transform existing types by iterating over their properties.

Basic Mapped Type:

type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

interface User {
  id: number;
  name: string;
}

type ReadonlyUser = Readonly<User>;
// Type: { readonly id: number; readonly name: string; }

Optional Properties:

type Partial<T> = {
  [P in keyof T]?: T[P];
};

type PartialUser = Partial<User>;
// Type: { id?: number; name?: string; }

Key Remapping:

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

interface Person {
  name: string;
  age: number;
}

type PersonGetters = Getters<Person>;
// Type: { getName: () => string; getAge: () => number; }

Filtering Properties:

type PickByType<T, U> = {
  [K in keyof T as T[K] extends U ? K : never]: T[K];
};

interface Mixed {
  id: number;
  name: string;
  age: number;
  active: boolean;
}

type OnlyNumbers = PickByType<Mixed, number>;
// Type: { id: number; age: number; }
4. Template Literal Types

Purpose: Create string-based types with pattern matching and transformation.

Basic Template Literal:

type EventName = "click" | "focus" | "blur";
type EventHandler = `on${Capitalize<EventName>}`;
// Type: "onClick" | "onFocus" | "onBlur"

String Manipulation:

type UppercaseGreeting = Uppercase<"hello">; // "HELLO"
type LowercaseGreeting = Lowercase<"HELLO">; // "hello"
type CapitalizedName = Capitalize<"john">; // "John"
type UncapitalizedName = Uncapitalize<"John">; // "john"

Path Building:

type Path<T> = T extends object
  ? {
      [K in keyof T]: K extends string ? `${K}` | `${K}.${Path<T[K]>}` : never;
    }[keyof T]
  : never;

interface Config {
  server: {
    host: string;
    port: number;
  };
  database: {
    url: string;
  };
}

type ConfigPath = Path<Config>;
// Type: "server" | "database" | "server.host" | "server.port" | "database.url"
5. Utility Types

Built-in Utility Types:

// Partial<T> - Make all properties optional
type PartialUser = Partial<User>;

// Required<T> - Make all properties required
type RequiredUser = Required<PartialUser>;

// Readonly<T> - Make all properties readonly
type ReadonlyUser = Readonly<User>;

// Pick<T, K> - Select specific properties
type UserName = Pick<User, "name" | "email">;

// Omit<T, K> - Remove specific properties
type UserWithoutPassword = Omit<User, "password">;

// Exclude<T, U> - Exclude types from union
type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"

// Extract<T, U> - Extract types from union
type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"

// NonNullable<T> - Exclude null and undefined
type T3 = NonNullable<string | null | undefined>; // string

// Record<K, T> - Create object type with keys K and values T
type PageInfo = Record<"home" | "about", { title: string }>;

Detailed worked examples and patterns

Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.

Best Practices

  1. Use unknown over any: Enforce type checking
  2. Prefer interface for object shapes: Better error messages
  3. Use type for unions and complex types: More flexible
  4. Leverage type inference: Let TypeScript infer when possible
  5. Create helper types: Build reusable type utilities
  6. Use const assertions: Preserve literal types
  7. Avoid type assertions: Use type guards instead
  8. Document complex types: Add JSDoc comments
  9. Use strict mode: Enable all strict compiler options
  10. Test your types: Use type tests to verify type behavior

Type Testing

// Type assertion tests
type AssertEqual<T, U> = [T] extends [U]
  ? [U] extends [T]
    ? true
    : false
  : false;

type Test1 = AssertEqual<string, string>; // true
type Test2 = AssertEqual<string, number>; // false
type Test3 = AssertEqual<string | number, string>; // false

// Expect error helper
type ExpectError<T extends never> = T;

// Example usage
type ShouldError = ExpectError<AssertEqual<string, number>>;

Common Pitfalls

  1. Over-using any: Defeats the purpose of TypeScript
  2. Ignoring strict null checks: Can lead to runtime errors
  3. Too complex types: Can slow down compilation
  4. Not using discriminated unions: Misses type narrowing opportunities
  5. Forgetting readonly modifiers: Allows unintended mutations
  6. Circular type references: Can cause compiler errors
  7. Not handling edge cases: Like empty arrays or null values

Performance Considerations

  • Avoid deeply nested conditional types
  • Use simple types when possible
  • Cache complex type computations
  • Limit recursion depth in recursive types
  • Use build tools to skip type checking in production
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## 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 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillExtract text, tables, metadataXberg Document Extractionxberg-io/xberg · by xberg-ioExtract text, tables, metadata, and images from 107 document formats (PDF, Office, images, HTML, email, archives, academic) using Xberg. Use when writing code that calls Xberg APIs in Python, Node.js/TypeScript, Rust, or CLI. Covers installation, extraction (sync/async), configuration (OCR, chunking, output format), batch processing, error handling, and plugins.★ 9.4k GitHub starsSkillMove code from one implementation to another functionCode migrationkucherenko/jscpd · by kucherenkoMove code from one implementation to another function by function, tests first and code second, and check two implementations of one app for parity, with jscpd --compare as the progress measure and a coverage map binding each function to its tests. Use when porting a library or app to another language or framework (Java to Kotlin, JavaScript to Rust, a Python library to TypeScript, an iOS app to Android), when asked what is left to port, or when comparing the Android and iOS versions of an app.★ 6.3k GitHub starsSkillManages Ahrefs API usage in Python using ahrefs-pythonOpenClaudia/openclaudia-skills · by OpenClaudiaManages Ahrefs API usage in Python using `ahrefs-python` library. Use when working with SEO / marketing related tasks or with data including backlinks, keywords, domain ratings, organic traffic, site audits, rank tracking, and brand monitoring. Covers `ahrefs-python` usage including AhrefsClient / AsyncAhrefsClient, typed request/response models, error handling, and all API sections.★ 705 GitHub starsMCPDocx LLM translatoradeudealfluence/adeu · by dealfluenceDocx ↔ LLM translator. Projects .docx office files to Markdown for editing. Projects edits back to OOXML as tracked changes (redlines). Python and Node.js implementations.★ 165 GitHub starsSkillCreate an Amazon-compliant white-background main imageAmazon White-Background Main Image · 亚马逊白底主图xianyu110/ecommerce-image-skills · by xianyu110Create an Amazon-compliant white-background main image (pure #FFFFFF background, product fills ≥85% of the frame, no text, props or watermark) from a product photo with GPT Image 2.5, then verify it with a Python check script. Use for Amazon/Walmart/eBay main images, 白底图, 白底主图, hero image, listing main photo.★ 92 GitHub starsMCPOfficial monorepo of SDKs, CLISendmux sdkSendmux/sendmux-sdk · by SendmuxOfficial monorepo of SDKs, CLI, and MCP servers for Sendmux email APIs across TypeScript, Python, Go, PHP, Rust, and Ruby.★ 65 GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars