Effective TypeScript Skill
Apply the 62 items from Dan Vanderkam's "Effective TypeScript" to review existing code and write new TypeScript. This skill operates in two modes: Review Mode (analyze code for violations) and Write Mode (produce idiomatic, well-typed TypeScript from scratch).
Reference Files
This skill includes categorized reference files covering all 62 items:
ref-01-getting-to-know-ts.md — Items 1-5: TS/JS relationship, compiler options, code generation, structural typing, any
ref-02-type-system.md — Items 6-18: editor, sets, type vs value space, declarations vs assertions, object wrappers, excess property checking, generics, readonly, mapped types
ref-03-type-inference.md — Items 19-27: inferable types, widening, narrowing, objects at once, aliases, async/await, context, functional constructs
ref-04-type-design.md — Items 28-37: valid states, Postel's Law, documentation, null perimeter, unions of interfaces, string types, branded types
ref-05-working-with-any.md — Items 38-44: narrowest scope, precise any variants, unsafe assertions, evolving any, unknown, monkey patching, type coverage
ref-06-type-declarations.md — Items 45-52: devDependencies, three versions, export types, TSDoc, this in callbacks, conditional types, mirror types, testing types
ref-07-writing-running-code.md — Items 53-57: ECMAScript features, iterating objects, DOM hierarchy, private, source maps
ref-08-migrating.md — Items 58-62: modern JS, @ts-check, allowJs, module-by-module, noImplicitAny
How to Use This Skill
Before responding, read the relevant reference files based on the code's topic. For a general review, read all files. For targeted work (e.g., type design), read the specific reference (e.g., ref-04-type-design.md).
Mode 1: Code Review
When the user asks you to review existing TypeScript code, follow this process:
Step 1: Read Relevant References
Determine which chapters apply to the code under review and read those reference files. If unsure, read all of them.
Step 2: Analyze the Code
Before listing issues, first ask: Is this code already applying Effective TypeScript principles? Look for positive signals:
- Tagged unions with a discriminant field (Item 28/32)
- Branded types for nominal typing (Item 37)
unknown for external data, narrowed before use (Item 42)
- Type assertions scoped inside well-typed wrapper functions (Item 40)
readonly on fields/parameters (Item 17)
async/await with typed return types (Item 25)
- TSDoc comments on public functions (Item 48)
Key rule — Item 40 interaction with Item 9: A type assertion (as T) inside a function that has a fully-typed signature is NOT a violation of Item 9. Item 40 explicitly endorses hiding unsafe assertions inside well-typed wrappers. Only flag as when it appears at a call-site or as an escape hatch on a public-facing value.
For each relevant item from the book, check whether the code follows or violates the guideline. Focus on:
- TypeScript Fundamentals (Items 1-5): Is
strict mode enabled? Is any used carelessly? Does structural typing cause surprises?
- Type System Usage (Items 6-18): Are type declarations preferred over assertions? Are object wrapper types avoided? Are
readonly and mapped types used appropriately?
- Type Inference (Items 19-27): Is inference relied upon where possible? Are
async/await used over callbacks? Are aliases consistent?
- Type Design (Items 28-37): Do types represent only valid states? Are string types replaced with literal unions? Are null values pushed to the perimeter?
- Working with any (Items 38-44): Is
any scoped as narrowly as possible? Is unknown used for truly unknown values? Are unsafe assertions hidden in well-typed wrappers?
- Type Declarations (Items 45-52): Are
@types in devDependencies? Are public API types exported? Is TSDoc used for comments?
- Code Execution (Items 53-57): Are ECMAScript features preferred over TypeScript-only equivalents? Is object iteration done safely?
- Migration (Items 58-62): Is modern JavaScript used as a baseline? Is migration done module-by-module?
Step 3: Calibrate Your Response
If the code is already well-typed:
- Open with acknowledgment of what is correct and which Items are applied
- Only note genuine issues; do not manufacture problems
- Any remaining observations must be clearly labeled as "optional polish" or "minor suggestion"
- Do NOT escalate a narrowly scoped assertion inside a well-typed function to Critical/Important
If the code has real issues:
For each issue found, report:
- Item number and name (e.g., "Item 9: Prefer Type Declarations to Type Assertions")
- Location in the code
- What's wrong (the anti-pattern)
- How to fix it (the TypeScript-idiomatic way)
- Priority: Critical (bugs/correctness), Important (maintainability), Suggestion (style)
Step 4: Provide Fixed Code (only when needed)
If there are real issues, offer a corrected version with comments explaining each change. If the code is already correct, you may offer a brief "what's great here" summary instead of a rewrite.
Mode 2: Writing New Code
When the user asks you to write new TypeScript code, apply these core practices:
Always Apply These Core Practices
Enable strict mode (Item 2). Never write TypeScript without "strict": true in tsconfig.json.
Prefer type declarations over assertions (Item 9). Use const x: MyType = value not const x = value as MyType.
Avoid object wrapper types (Item 10). Use string, number, boolean — never String, Number, Boolean.
Use types that represent only valid states (Item 28). Eliminate impossible states at the type level with tagged unions.
Push null to the perimeter (Item 31). Don't scatter T | null throughout — handle nullability at boundaries.
Prefer unions of interfaces to interfaces of unions (Item 32). Model tagged unions instead of interfaces with optional fields that have implicit relationships.
Replace plain string types with string literal unions (Item 33). type Direction = 'north' | 'south' | 'east' | 'west' not string.
Generate types from APIs and specs, not data (Item 35). Use quicktype or OpenAPI code generation — don't hand-write types for external data.
Use unknown instead of any for values with unknown type (Item 42). unknown forces callers to narrow before use.
Scope any as narrowly as possible (Item 38). Apply it to a single value, never a whole object or module.
Use readonly to prevent mutation bugs (Item 17). Prefer readonly on function parameters accepting arrays, and on class fields that should not be reassigned.
Use async/await over raw Promises and callbacks (Item 25). It produces cleaner inferred types and clearer code.
Use type aliases to avoid repeating yourself (Item 14). DRY applies to types too — extract shared structure with Pick, Omit, mapped types.
Export all types that appear in public APIs (Item 47). Don't force users to reconstruct types with ReturnType<> or Parameters<>.
Use TSDoc for API comments (Item 48). /** */ comments appear in editor tooltips; @param, @returns, @deprecated are recognized by tooling.
Type Structure Template
// Prefer interfaces for object shapes (extendable); type aliases for unions/intersections
interface User {
readonly id: UserId; // Item 17: readonly on fields that shouldn't change
name: string;
email: string;
}
// Branded type for nominal typing (Item 37)
type UserId = string & { readonly __brand: 'UserId' };
// Tagged union — only valid states representable (Item 28, 32)
type RequestState<T> =
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; message: string };
// unknown, not any, for values from external sources (Item 42)
function parseResponse(json: string): unknown {
return JSON.parse(json);
}
// async/await over callbacks (Item 25)
async function fetchUser(id: UserId): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json() as User; // narrowly scoped assertion inside well-typed function (Item 40)
}
any Guidelines
- If
any is unavoidable, apply it to the smallest possible scope (Item 38)
- Prefer
unknown for values received from external sources (Item 42)
- Hide unsafe assertions inside well-typed wrapper functions (Item 40)
- Track type coverage with
type-coverage CLI to prevent regressions (Item 44)
Priority of Items by Impact
Critical (Correctness & Bugs)
- Item 2: Enable
strict mode — noImplicitAny and strictNullChecks prevent whole classes of bugs
- Item 9: Prefer declarations to assertions — but see Item 40: assertions inside well-typed wrappers are fine
- Item 28: Types that always represent valid states — impossible states cause runtime errors
- Item 31: Push null to the perimeter — scattered nullability causes null dereferences
- Item 42: Use
unknown instead of any — any silently disables type checking
Item 40 exception: raw as SomeType inside a function with a fully-typed signature is explicitly endorsed by Item 40. It is acceptable and should NOT be flagged as a Critical or Important violation. At most, note it as a minor optional polish item (suggest a runtime validator like zod as a complement).
Important (Maintainability)
- Item 13: Know the differences between
type and interface
- Item 14: Use type operations and generics to avoid repetition
- Item 17: Use
readonly to prevent mutation bugs
- Item 25: Use
async/await over callbacks
- Item 32: Prefer unions of interfaces to interfaces of unions
- Item 33: Prefer string literal unions over plain
string
- Item 47: Export all types that appear in public APIs
- Item 48: Use TSDoc for API comments
Suggestions (Polish & Optimization)
- Item 19: Omit inferable types to reduce clutter
- Item 35: Generate types from APIs and specs
- Item 37: Consider brands for nominal typing
- Item 44: Track type coverage
- Item 53: Prefer ECMAScript features over TypeScript-only equivalents
1---2name: effective-typescript3description: Review existing TypeScript code and write new TypeScript following the 62 items from "Effective TypeScript" by Dan Vanderkam. Use when writing TypeScript, reviewing TypeScript code, working with type design, avoiding any, managing type declarations, or migrating JavaScript to TypeScript. Trigger on: "TypeScript best practices", "type safety", "any", "type assertions", "type design", "strict mode", "TypeScript review", "migrate to TypeScript".4---56# Effective TypeScript Skill78Apply the 62 items from Dan Vanderkam's "Effective TypeScript" to review existing code and write new TypeScript. This skill operates in two modes: **Review Mode** (analyze code for violations) and **Write Mode** (produce idiomatic, well-typed TypeScript from scratch).910## Reference Files1112This skill includes categorized reference files covering all 62 items:1314- `ref-01-getting-to-know-ts.md` — Items 1-5: TS/JS relationship, compiler options, code generation, structural typing, any15- `ref-02-type-system.md` — Items 6-18: editor, sets, type vs value space, declarations vs assertions, object wrappers, excess property checking, generics, readonly, mapped types16- `ref-03-type-inference.md` — Items 19-27: inferable types, widening, narrowing, objects at once, aliases, async/await, context, functional constructs17- `ref-04-type-design.md` — Items 28-37: valid states, Postel's Law, documentation, null perimeter, unions of interfaces, string types, branded types18- `ref-05-working-with-any.md` — Items 38-44: narrowest scope, precise any variants, unsafe assertions, evolving any, unknown, monkey patching, type coverage19- `ref-06-type-declarations.md` — Items 45-52: devDependencies, three versions, export types, TSDoc, this in callbacks, conditional types, mirror types, testing types20- `ref-07-writing-running-code.md` — Items 53-57: ECMAScript features, iterating objects, DOM hierarchy, private, source maps21- `ref-08-migrating.md` — Items 58-62: modern JS, @ts-check, allowJs, module-by-module, noImplicitAny2223## How to Use This Skill2425**Before responding**, read the relevant reference files based on the code's topic. For a general review, read all files. For targeted work (e.g., type design), read the specific reference (e.g., `ref-04-type-design.md`).2627---2829## Mode 1: Code Review3031When the user asks you to **review** existing TypeScript code, follow this process:3233### Step 1: Read Relevant References34Determine which chapters apply to the code under review and read those reference files. If unsure, read all of them.3536### Step 2: Analyze the Code37Before listing issues, first ask: **Is this code already applying Effective TypeScript principles?** Look for positive signals:38- Tagged unions with a discriminant field (Item 28/32)39- Branded types for nominal typing (Item 37)40- `unknown` for external data, narrowed before use (Item 42)41- Type assertions scoped inside well-typed wrapper functions (Item 40)42- `readonly` on fields/parameters (Item 17)43- `async`/`await` with typed return types (Item 25)44- TSDoc comments on public functions (Item 48)4546**Key rule — Item 40 interaction with Item 9:** A type assertion (`as T`) inside a function that has a fully-typed signature is NOT a violation of Item 9. Item 40 explicitly endorses hiding unsafe assertions inside well-typed wrappers. Only flag `as` when it appears at a call-site or as an escape hatch on a public-facing value.4748For each relevant item from the book, check whether the code follows or violates the guideline. Focus on:49501. **TypeScript Fundamentals** (Items 1-5): Is `strict` mode enabled? Is `any` used carelessly? Does structural typing cause surprises?512. **Type System Usage** (Items 6-18): Are type declarations preferred over assertions? Are object wrapper types avoided? Are `readonly` and mapped types used appropriately?523. **Type Inference** (Items 19-27): Is inference relied upon where possible? Are `async`/`await` used over callbacks? Are aliases consistent?534. **Type Design** (Items 28-37): Do types represent only valid states? Are string types replaced with literal unions? Are null values pushed to the perimeter?545. **Working with any** (Items 38-44): Is `any` scoped as narrowly as possible? Is `unknown` used for truly unknown values? Are unsafe assertions hidden in well-typed wrappers?556. **Type Declarations** (Items 45-52): Are `@types` in devDependencies? Are public API types exported? Is TSDoc used for comments?567. **Code Execution** (Items 53-57): Are ECMAScript features preferred over TypeScript-only equivalents? Is object iteration done safely?578. **Migration** (Items 58-62): Is modern JavaScript used as a baseline? Is migration done module-by-module?5859### Step 3: Calibrate Your Response6061**If the code is already well-typed:**62- Open with acknowledgment of what is correct and which Items are applied63- Only note genuine issues; do not manufacture problems64- Any remaining observations must be clearly labeled as "optional polish" or "minor suggestion"65- Do NOT escalate a narrowly scoped assertion inside a well-typed function to Critical/Important6667**If the code has real issues:**68For each issue found, report:69- **Item number and name** (e.g., "Item 9: Prefer Type Declarations to Type Assertions")70- **Location** in the code71- **What's wrong** (the anti-pattern)72- **How to fix it** (the TypeScript-idiomatic way)73- **Priority**: Critical (bugs/correctness), Important (maintainability), Suggestion (style)7475### Step 4: Provide Fixed Code (only when needed)76If there are real issues, offer a corrected version with comments explaining each change. If the code is already correct, you may offer a brief "what's great here" summary instead of a rewrite.7778---7980## Mode 2: Writing New Code8182When the user asks you to **write** new TypeScript code, apply these core practices:8384### Always Apply These Core Practices85861. **Enable strict mode** (Item 2). Never write TypeScript without `"strict": true` in tsconfig.json.87882. **Prefer type declarations over assertions** (Item 9). Use `const x: MyType = value` not `const x = value as MyType`.89903. **Avoid object wrapper types** (Item 10). Use `string`, `number`, `boolean` — never `String`, `Number`, `Boolean`.91924. **Use types that represent only valid states** (Item 28). Eliminate impossible states at the type level with tagged unions.93945. **Push null to the perimeter** (Item 31). Don't scatter `T | null` throughout — handle nullability at boundaries.95966. **Prefer unions of interfaces to interfaces of unions** (Item 32). Model tagged unions instead of interfaces with optional fields that have implicit relationships.97987. **Replace plain string types with string literal unions** (Item 33). `type Direction = 'north' | 'south' | 'east' | 'west'` not `string`.991008. **Generate types from APIs and specs, not data** (Item 35). Use `quicktype` or OpenAPI code generation — don't hand-write types for external data.1011029. **Use `unknown` instead of `any` for values with unknown type** (Item 42). `unknown` forces callers to narrow before use.10310410. **Scope `any` as narrowly as possible** (Item 38). Apply it to a single value, never a whole object or module.10510611. **Use `readonly` to prevent mutation bugs** (Item 17). Prefer `readonly` on function parameters accepting arrays, and on class fields that should not be reassigned.10710812. **Use `async`/`await` over raw Promises and callbacks** (Item 25). It produces cleaner inferred types and clearer code.10911013. **Use type aliases to avoid repeating yourself** (Item 14). DRY applies to types too — extract shared structure with `Pick`, `Omit`, mapped types.11111214. **Export all types that appear in public APIs** (Item 47). Don't force users to reconstruct types with `ReturnType<>` or `Parameters<>`.11311415. **Use TSDoc for API comments** (Item 48). `/** */` comments appear in editor tooltips; `@param`, `@returns`, `@deprecated` are recognized by tooling.115116### Type Structure Template117118```typescript119// Prefer interfaces for object shapes (extendable); type aliases for unions/intersections120interface User {121 readonly id: UserId; // Item 17: readonly on fields that shouldn't change122 name: string;123 email: string;124}125126// Branded type for nominal typing (Item 37)127type UserId = string & { readonly __brand: 'UserId' };128129// Tagged union — only valid states representable (Item 28, 32)130type RequestState<T> =131 | { status: 'loading' }132 | { status: 'success'; data: T }133 | { status: 'error'; message: string };134135// unknown, not any, for values from external sources (Item 42)136function parseResponse(json: string): unknown {137 return JSON.parse(json);138}139140// async/await over callbacks (Item 25)141async function fetchUser(id: UserId): Promise<User> {142 const response = await fetch(`/api/users/${id}`);143 if (!response.ok) throw new Error(`HTTP ${response.status}`);144 return response.json() as User; // narrowly scoped assertion inside well-typed function (Item 40)145}146```147148### any Guidelines149- If `any` is unavoidable, apply it to the smallest possible scope (Item 38)150- Prefer `unknown` for values received from external sources (Item 42)151- Hide unsafe assertions inside well-typed wrapper functions (Item 40)152- Track type coverage with `type-coverage` CLI to prevent regressions (Item 44)153154---155156## Priority of Items by Impact157158### Critical (Correctness & Bugs)159- Item 2: Enable `strict` mode — `noImplicitAny` and `strictNullChecks` prevent whole classes of bugs160- Item 9: Prefer declarations to assertions — **but see Item 40**: assertions inside well-typed wrappers are fine161- Item 28: Types that always represent valid states — impossible states cause runtime errors162- Item 31: Push null to the perimeter — scattered nullability causes null dereferences163- Item 42: Use `unknown` instead of `any` — `any` silently disables type checking164165> **Item 40 exception:** `raw as SomeType` inside a function with a fully-typed signature is explicitly endorsed by Item 40. It is acceptable and should NOT be flagged as a Critical or Important violation. At most, note it as a minor optional polish item (suggest a runtime validator like zod as a complement).166167### Important (Maintainability)168- Item 13: Know the differences between `type` and `interface`169- Item 14: Use type operations and generics to avoid repetition170- Item 17: Use `readonly` to prevent mutation bugs171- Item 25: Use `async`/`await` over callbacks172- Item 32: Prefer unions of interfaces to interfaces of unions173- Item 33: Prefer string literal unions over plain `string`174- Item 47: Export all types that appear in public APIs175- Item 48: Use TSDoc for API comments176177### Suggestions (Polish & Optimization)178- Item 19: Omit inferable types to reduce clutter179- Item 35: Generate types from APIs and specs180- Item 37: Consider brands for nominal typing181- Item 44: Track type coverage182- Item 53: Prefer ECMAScript features over TypeScript-only equivalents