TypeScript Operations
Comprehensive TypeScript skill covering the type system, generics, and production patterns.
Ecosystem facts verified as of 2026-08-08 (TypeScript 7, Zod 4, Valibot 1).
Staleness check: python scripts/check-typescript-facts.py --offline asserts the
catalogued version-bearing facts (TypeScript major, zod, valibot) are still named in the
prose and the dated currency note above is present; run --live to confirm each package's
npm major still matches the documented major. Catalog: assets/typescript-facts.json.
Type Narrowing Decision Tree
How to narrow a type?
│
├─ Primitive type check
│ └─ typeof: typeof x === "string"
│
├─ Instance check
│ └─ instanceof: x instanceof Date
│
├─ Property existence
│ └─ in: "email" in user
│
├─ Discriminated union
│ └─ switch on literal field: switch (event.type)
│
├─ Null/undefined check
│ └─ Truthiness: if (x) or if (x != null)
│
├─ Custom logic
│ └─ Type predicate: function isUser(x: unknown): x is User
│
└─ Assertion (you know better than TS)
└─ as: value as string (escape hatch, avoid when possible)
Type Guard Example
interface Dog { bark(): void; breed: string }
interface Cat { meow(): void; color: string }
function isDog(pet: Dog | Cat): pet is Dog {
return "bark" in pet;
}
function handlePet(pet: Dog | Cat) {
if (isDog(pet)) {
pet.bark(); // TS knows it's Dog here
} else {
pet.meow(); // TS knows it's Cat here
}
}
Discriminated Unions
type Result<T> =
| { status: "success"; data: T }
| { status: "error"; error: string }
| { status: "loading" };
function handle<T>(result: Result<T>) {
switch (result.status) {
case "success": return result.data; // data is available
case "error": throw new Error(result.error); // error is available
case "loading": return null;
}
// Exhaustiveness check: result is `never` here
const _exhaustive: never = result;
}
Utility Types Cheat Sheet
| Utility |
What It Does |
Example |
Partial<T> |
All props optional |
Partial<User> for update payloads |
Required<T> |
All props required |
Required<Config> for validated config |
Readonly<T> |
All props readonly |
Readonly<State> for immutable state |
Pick<T, K> |
Select specific props |
Pick<User, "id" | "name"> |
Omit<T, K> |
Remove specific props |
Omit<User, "password"> |
Record<K, V> |
Object with typed keys/values |
Record<string, number> |
Exclude<U, E> |
Remove types from union |
Exclude<Status, "deleted"> |
Extract<U, E> |
Keep types from union |
Extract<Event, { type: "click" }> |
NonNullable<T> |
Remove null/undefined |
NonNullable<string | null> |
ReturnType<F> |
Function return type |
ReturnType<typeof fetchUser> |
Parameters<F> |
Function params as tuple |
Parameters<typeof createUser> |
Awaited<T> |
Unwrap Promise type |
Awaited<Promise<User>> = User |
Generic Patterns
Constrained Generics
// Basic constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// Multiple constraints
function merge<T extends object, U extends object>(a: T, b: U): T & U {
return { ...a, ...b };
}
// Default generic type
type ApiResponse<T = unknown> = {
data: T;
status: number;
};
Conditional Types
// Basic conditional
type IsString<T> = T extends string ? true : false;
// infer keyword - extract inner type
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type UnwrapArray<T> = T extends (infer U)[] ? U : T;
// Distributive conditional (distributes over union)
type ToArray<T> = T extends any ? T[] : never;
// ToArray<string | number> = string[] | number[]
// Prevent distribution with wrapping
type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;
// ToArrayNonDist<string | number> = (string | number)[]
Mapped Types
// Make all properties optional and nullable
type Nullable<T> = { [K in keyof T]: T[K] | null };
// Add prefix to keys
type Prefixed<T, P extends string> = {
[K in keyof T as `${P}${Capitalize<string & K>}`]: T[K];
};
// Prefixed<{ name: string }, "get"> = { getName: string }
// Filter keys by value type
type StringKeys<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
Deep dive: Load ./references/generics-patterns.md for advanced type-level programming, recursive types, template literal types.
Modern Language Features (TypeScript 5.x → 6.0)
| Feature |
Since |
What It Gives You |
satisfies operator |
4.9 |
Check a value against a type without widening it |
| Standard (TC39) decorators |
5.0 |
@decorator on classes/methods without experimentalDecorators |
const type parameters |
5.0 |
function f<const T>(x: T) infers literal types without as const at call sites |
using declarations |
5.2 |
Explicit resource management (Symbol.dispose), auto-cleanup at scope exit |
| Inferred type predicates |
5.5 |
arr.filter(x => x !== null) narrows without a hand-written x is T guard |
verbatimModuleSyntax |
5.0 |
Enforces import type for type-only imports — replaces importsNotUsedAsValues |
// const type parameters (5.0) - literal inference without as const
function routes<const T extends readonly string[]>(paths: T): T { return paths; }
const r = routes(["/home", "/about"]); // readonly ["/home", "/about"], not string[]
// using declarations (5.2) - deterministic cleanup
function readConfig() {
using file = openFile("config.json"); // file[Symbol.dispose]() runs at scope exit
return parse(file.contents);
}
// Inferred type predicates (5.5) - no manual guard needed
const names = ["a", null, "b"].filter(x => x !== null); // string[], not (string | null)[]
TypeScript 6.0 (The Bridge Release)
TS 6.0 is the last release on the JavaScript-based compiler — it exists to bridge to the
native (Go) compiler in TS 7, so its headline is stricter, modernised defaults:
strict: true is the default — a tsconfig that never set it now gets full strict checks
- Defaults modernised:
module: esnext, target: es2025; es2025 lib ships types for Temporal, Map.getOrInsert, RegExp.escape
- Legacy options removed:
moduleResolution: classic; module: amd/umd/system/none; minimum target is now ES2015 (es5 deprecated)
- Interop always on:
esModuleInterop / allowSyntheticDefaultImports can no longer be disabled
- New
--stableTypeOrdering flag eases 6.0 → 7.0 migration diffing
TypeScript 7 (Current Major — Native Compiler)
TS 7 is the Go-native rewrite (formerly tsgo), stable on npm since 2026-07-08.
Same checking semantics, ~8–16× faster typechecks — but the package ships only a
bin/tsc shim, no JavaScript compiler API: require('typescript') throws
MODULE_NOT_FOUND on 7.0.x (the API returns in 7.1+). Consequences that gate
adoption:
- Repo tooling using the TS programmatic API (
ts.createSourceFile, custom lint
scripts, codemods, typescript-eslint) must go AST-free, switch parser, or pin an alias
- Tools typechecking embedded languages (vue-tsc, svelte-check, Astro, MDX) are
pinned to TS 6 until they port to the 7.1+ API — a real stack-selection input
- A tsconfig already on TS 6 defaults adopts directly (the 6.0 bridge is skippable);
baseUrl is a hard error (TS5102)
- Running a
typescript5 fallback alias alongside 7 makes bare npx tsc ambiguous —
scripts must use explicit compiler paths during the soak
Deep dive: Load ./references/ts7-native-compiler.md for the no-JS-API workarounds,
dual-install bin ambiguity, ecosystem lockout table, measured adoption benchmarks (12.1×),
and the go/no-go checklist.
tsconfig Quick Reference
{
"compilerOptions": {
// Strict mode (default in TS 6; state it explicitly anyway)
"strict": true, // Enables all strict checks
"noUncheckedIndexedAccess": true, // arr[0] is T | undefined
// Module system (TS 6 defaults to module: esnext; interop is always on)
"module": "esnext", // or "nodenext" for Node
"moduleResolution": "bundler", // or "nodenext"
// Output (TS 6 defaults target to es2025; min supported is es2015)
"target": "es2022",
"outDir": "dist",
"declaration": true, // Generate .d.ts
"sourceMap": true,
// Paths — tsconfig-relative; don't add baseUrl (TS 7 hard-errors on it, TS5102)
"paths": { "@/*": ["./src/*"] },
// Strictness extras
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
Deep dive: Load ./references/config-strict.md for strict mode migration, monorepo config, project references.
Common Gotchas
| Gotcha |
Why |
Fix |
any leaks |
any disables type checking for everything it touches |
Use unknown + narrowing instead |
as assertions hide bugs |
Assertion doesn't check at runtime |
Use type guards or validation (Zod) |
enum quirks |
Numeric enums are not type-safe, reverse mappings confuse |
Use as const objects or string literal unions |
object vs Record vs {} |
{} matches any non-null value, object is non-primitive |
Use Record<string, unknown> for "any object" |
| Array index access |
arr[999] returns T not T | undefined by default |
Enable noUncheckedIndexedAccess |
| Optional vs undefined |
{ x?: string } allows missing key, { x: string | undefined } requires key |
Be explicit about which you mean |
! non-null assertion |
Silences null checks, no runtime effect |
Use ?? defaultValue or proper null check |
| Structural typing surprise |
{ a: 1, b: 2 } assignable to { a: number } |
Use branded types for nominal typing |
Branded / Nominal Types
// Prevent accidentally mixing types that are structurally identical
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function createUserId(id: string): UserId { return id as UserId; }
function getUser(id: UserId) { /* ... */ }
const userId = createUserId("u-123");
const orderId = "o-456" as OrderId;
getUser(userId); // OK
getUser(orderId); // Error: OrderId not assignable to UserId
Runtime Validation (Zod 4)
import { z } from "zod";
// Define schema (Zod 4: string formats are top-level - z.email(), not z.string().email())
const UserSchema = z.object({
id: z.number(),
name: z.string().min(1),
email: z.email(),
role: z.enum(["admin", "user"]),
settings: z.object({
theme: z.enum(["light", "dark"]).default("light"),
}).optional(),
});
// Infer type from schema
type User = z.infer<typeof UserSchema>;
// Validate
const user = UserSchema.parse(untrustedData); // throws on invalid
const result = UserSchema.safeParse(untrustedData); // returns { success, data/error }
Zod 4 changes to know (if you learned Zod 3): string formats moved to the top level
(z.email(), z.uuid(), z.url() — the z.string().email() method form is deprecated);
error customisation unified under a single error param (invalid_type_error /
required_error dropped); much faster parsing and a tree-shakeable zod/mini entry point.
Reference Files
Load these for deep-dive topics. Each is self-contained.
| Reference |
When to Load |
./references/type-system.md |
Advanced types, branded types, type-level programming, satisfies operator |
./references/generics-patterns.md |
Generic constraints, conditional types, mapped types, template literals, recursive types |
./references/utility-types.md |
All built-in utility types with examples, custom utility types |
./references/config-strict.md |
tsconfig deep dive, strict mode migration, project references, monorepo setup |
./references/ts7-native-compiler.md |
Adopting the TS 7 native (Go) compiler: no JS API, bin ambiguity, ecosystem lockout, benchmarked go/no-go |
./references/ecosystem.md |
Zod/Valibot, type-safe API clients, ORM types, testing with Vitest |
See Also
testing-ops - Cross-language testing strategies
ci-cd-ops - TypeScript CI pipelines, type checking in CI
1---2name: typescript-ops3description: "TypeScript type system, generics, utility types, strict mode, and ecosystem patterns. Use for: typescript, ts, type, generic, utility type, Partial, Pick, Omit, Record, Exclude, Extract, ReturnType, Parameters, keyof, typeof, infer, mapped type, conditional type, template literal type, discriminated union, type guard, type assertion, type narrowing, tsconfig, strict mode, declaration file, zod, valibot, typescript 7, tsgo, native compiler."4license: MIT5allowed-tools: "Read Write Bash"6metadata:7 author: claude-mods8 related-skills: react-ops, testing-ops9---1011# TypeScript Operations1213Comprehensive TypeScript skill covering the type system, generics, and production patterns.1415> Ecosystem facts verified as of 2026-08-08 (TypeScript 7, Zod 4, Valibot 1).1617**Staleness check:** `python scripts/check-typescript-facts.py --offline` asserts the18catalogued version-bearing facts (TypeScript major, zod, valibot) are still named in the19prose and the dated currency note above is present; run `--live` to confirm each package's20npm major still matches the documented major. Catalog: `assets/typescript-facts.json`.2122## Type Narrowing Decision Tree2324```25How to narrow a type?26│27├─ Primitive type check28│ └─ typeof: typeof x === "string"29│30├─ Instance check31│ └─ instanceof: x instanceof Date32│33├─ Property existence34│ └─ in: "email" in user35│36├─ Discriminated union37│ └─ switch on literal field: switch (event.type)38│39├─ Null/undefined check40│ └─ Truthiness: if (x) or if (x != null)41│42├─ Custom logic43│ └─ Type predicate: function isUser(x: unknown): x is User44│45└─ Assertion (you know better than TS)46 └─ as: value as string (escape hatch, avoid when possible)47```4849### Type Guard Example5051```typescript52interface Dog { bark(): void; breed: string }53interface Cat { meow(): void; color: string }5455function isDog(pet: Dog | Cat): pet is Dog {56 return "bark" in pet;57}5859function handlePet(pet: Dog | Cat) {60 if (isDog(pet)) {61 pet.bark(); // TS knows it's Dog here62 } else {63 pet.meow(); // TS knows it's Cat here64 }65}66```6768### Discriminated Unions6970```typescript71type Result<T> =72 | { status: "success"; data: T }73 | { status: "error"; error: string }74 | { status: "loading" };7576function handle<T>(result: Result<T>) {77 switch (result.status) {78 case "success": return result.data; // data is available79 case "error": throw new Error(result.error); // error is available80 case "loading": return null;81 }82 // Exhaustiveness check: result is `never` here83 const _exhaustive: never = result;84}85```8687## Utility Types Cheat Sheet8889| Utility | What It Does | Example |90|---------|-------------|---------|91| `Partial<T>` | All props optional | `Partial<User>` for update payloads |92| `Required<T>` | All props required | `Required<Config>` for validated config |93| `Readonly<T>` | All props readonly | `Readonly<State>` for immutable state |94| `Pick<T, K>` | Select specific props | `Pick<User, "id" \| "name">` |95| `Omit<T, K>` | Remove specific props | `Omit<User, "password">` |96| `Record<K, V>` | Object with typed keys/values | `Record<string, number>` |97| `Exclude<U, E>` | Remove types from union | `Exclude<Status, "deleted">` |98| `Extract<U, E>` | Keep types from union | `Extract<Event, { type: "click" }>` |99| `NonNullable<T>` | Remove null/undefined | `NonNullable<string \| null>` |100| `ReturnType<F>` | Function return type | `ReturnType<typeof fetchUser>` |101| `Parameters<F>` | Function params as tuple | `Parameters<typeof createUser>` |102| `Awaited<T>` | Unwrap Promise type | `Awaited<Promise<User>>` = `User` |103104## Generic Patterns105106### Constrained Generics107108```typescript109// Basic constraint110function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {111 return obj[key];112}113114// Multiple constraints115function merge<T extends object, U extends object>(a: T, b: U): T & U {116 return { ...a, ...b };117}118119// Default generic type120type ApiResponse<T = unknown> = {121 data: T;122 status: number;123};124```125126### Conditional Types127128```typescript129// Basic conditional130type IsString<T> = T extends string ? true : false;131132// infer keyword - extract inner type133type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;134type UnwrapArray<T> = T extends (infer U)[] ? U : T;135136// Distributive conditional (distributes over union)137type ToArray<T> = T extends any ? T[] : never;138// ToArray<string | number> = string[] | number[]139140// Prevent distribution with wrapping141type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;142// ToArrayNonDist<string | number> = (string | number)[]143```144145### Mapped Types146147```typescript148// Make all properties optional and nullable149type Nullable<T> = { [K in keyof T]: T[K] | null };150151// Add prefix to keys152type Prefixed<T, P extends string> = {153 [K in keyof T as `${P}${Capitalize<string & K>}`]: T[K];154};155// Prefixed<{ name: string }, "get"> = { getName: string }156157// Filter keys by value type158type StringKeys<T> = {159 [K in keyof T as T[K] extends string ? K : never]: T[K];160};161```162163**Deep dive**: Load `./references/generics-patterns.md` for advanced type-level programming, recursive types, template literal types.164165## Modern Language Features (TypeScript 5.x → 6.0)166167| Feature | Since | What It Gives You |168|---------|-------|-------------------|169| `satisfies` operator | 4.9 | Check a value against a type without widening it |170| Standard (TC39) decorators | 5.0 | `@decorator` on classes/methods without `experimentalDecorators` |171| `const` type parameters | 5.0 | `function f<const T>(x: T)` infers literal types without `as const` at call sites |172| `using` declarations | 5.2 | Explicit resource management (`Symbol.dispose`), auto-cleanup at scope exit |173| Inferred type predicates | 5.5 | `arr.filter(x => x !== null)` narrows without a hand-written `x is T` guard |174| `verbatimModuleSyntax` | 5.0 | Enforces `import type` for type-only imports — replaces `importsNotUsedAsValues` |175176```typescript177// const type parameters (5.0) - literal inference without as const178function routes<const T extends readonly string[]>(paths: T): T { return paths; }179const r = routes(["/home", "/about"]); // readonly ["/home", "/about"], not string[]180181// using declarations (5.2) - deterministic cleanup182function readConfig() {183 using file = openFile("config.json"); // file[Symbol.dispose]() runs at scope exit184 return parse(file.contents);185}186187// Inferred type predicates (5.5) - no manual guard needed188const names = ["a", null, "b"].filter(x => x !== null); // string[], not (string | null)[]189```190191### TypeScript 6.0 (The Bridge Release)192193TS 6.0 is the last release on the JavaScript-based compiler — it exists to bridge to the194native (Go) compiler in TS 7, so its headline is stricter, modernised defaults:195196- **`strict: true` is the default** — a tsconfig that never set it now gets full strict checks197- **Defaults modernised**: `module: esnext`, `target: es2025`; `es2025` lib ships types for Temporal, `Map.getOrInsert`, `RegExp.escape`198- **Legacy options removed**: `moduleResolution: classic`; `module: amd/umd/system/none`; minimum `target` is now ES2015 (`es5` deprecated)199- **Interop always on**: `esModuleInterop` / `allowSyntheticDefaultImports` can no longer be disabled200- New `--stableTypeOrdering` flag eases 6.0 → 7.0 migration diffing201202### TypeScript 7 (Current Major — Native Compiler)203204TS 7 is the Go-native rewrite (formerly `tsgo`), stable on npm since 2026-07-08.205Same checking semantics, ~8–16× faster typechecks — but the package ships **only a206`bin/tsc` shim, no JavaScript compiler API**: `require('typescript')` throws207`MODULE_NOT_FOUND` on 7.0.x (the API returns in 7.1+). Consequences that gate208adoption:209210- Repo tooling using the TS programmatic API (`ts.createSourceFile`, custom lint211 scripts, codemods, typescript-eslint) must go AST-free, switch parser, or pin an alias212- Tools typechecking embedded languages (vue-tsc, svelte-check, Astro, MDX) are213 pinned to TS 6 until they port to the 7.1+ API — a real stack-selection input214- A tsconfig already on TS 6 defaults adopts directly (the 6.0 bridge is skippable);215 `baseUrl` is a hard error (TS5102)216- Running a `typescript5` fallback alias alongside 7 makes bare `npx tsc` ambiguous —217 scripts must use explicit compiler paths during the soak218219**Deep dive**: Load `./references/ts7-native-compiler.md` for the no-JS-API workarounds,220dual-install bin ambiguity, ecosystem lockout table, measured adoption benchmarks (12.1×),221and the go/no-go checklist.222223## tsconfig Quick Reference224225```jsonc226{227 "compilerOptions": {228 // Strict mode (default in TS 6; state it explicitly anyway)229 "strict": true, // Enables all strict checks230 "noUncheckedIndexedAccess": true, // arr[0] is T | undefined231232 // Module system (TS 6 defaults to module: esnext; interop is always on)233 "module": "esnext", // or "nodenext" for Node234 "moduleResolution": "bundler", // or "nodenext"235236 // Output (TS 6 defaults target to es2025; min supported is es2015)237 "target": "es2022",238 "outDir": "dist",239 "declaration": true, // Generate .d.ts240 "sourceMap": true,241242 // Paths — tsconfig-relative; don't add baseUrl (TS 7 hard-errors on it, TS5102)243 "paths": { "@/*": ["./src/*"] },244245 // Strictness extras246 "noUnusedLocals": true,247 "noUnusedParameters": true,248 "noFallthroughCasesInSwitch": true,249 "forceConsistentCasingInFileNames": true250 },251 "include": ["src"],252 "exclude": ["node_modules", "dist"]253}254```255256**Deep dive**: Load `./references/config-strict.md` for strict mode migration, monorepo config, project references.257258## Common Gotchas259260| Gotcha | Why | Fix |261|--------|-----|-----|262| `any` leaks | `any` disables type checking for everything it touches | Use `unknown` + narrowing instead |263| `as` assertions hide bugs | Assertion doesn't check at runtime | Use type guards or validation (Zod) |264| `enum` quirks | Numeric enums are not type-safe, reverse mappings confuse | Use `as const` objects or string literal unions |265| `object` vs `Record` vs `{}` | `{}` matches any non-null value, `object` is non-primitive | Use `Record<string, unknown>` for "any object" |266| Array index access | `arr[999]` returns `T` not `T \| undefined` by default | Enable `noUncheckedIndexedAccess` |267| Optional vs undefined | `{ x?: string }` allows missing key, `{ x: string \| undefined }` requires key | Be explicit about which you mean |268| `!` non-null assertion | Silences null checks, no runtime effect | Use `?? defaultValue` or proper null check |269| Structural typing surprise | `{ a: 1, b: 2 }` assignable to `{ a: number }` | Use branded types for nominal typing |270271## Branded / Nominal Types272273```typescript274// Prevent accidentally mixing types that are structurally identical275type UserId = string & { readonly __brand: "UserId" };276type OrderId = string & { readonly __brand: "OrderId" };277278function createUserId(id: string): UserId { return id as UserId; }279280function getUser(id: UserId) { /* ... */ }281282const userId = createUserId("u-123");283const orderId = "o-456" as OrderId;284285getUser(userId); // OK286getUser(orderId); // Error: OrderId not assignable to UserId287```288289## Runtime Validation (Zod 4)290291```typescript292import { z } from "zod";293294// Define schema (Zod 4: string formats are top-level - z.email(), not z.string().email())295const UserSchema = z.object({296 id: z.number(),297 name: z.string().min(1),298 email: z.email(),299 role: z.enum(["admin", "user"]),300 settings: z.object({301 theme: z.enum(["light", "dark"]).default("light"),302 }).optional(),303});304305// Infer type from schema306type User = z.infer<typeof UserSchema>;307308// Validate309const user = UserSchema.parse(untrustedData); // throws on invalid310const result = UserSchema.safeParse(untrustedData); // returns { success, data/error }311```312313**Zod 4 changes to know** (if you learned Zod 3): string formats moved to the top level314(`z.email()`, `z.uuid()`, `z.url()` — the `z.string().email()` method form is deprecated);315error customisation unified under a single `error` param (`invalid_type_error` /316`required_error` dropped); much faster parsing and a tree-shakeable `zod/mini` entry point.317318## Reference Files319320Load these for deep-dive topics. Each is self-contained.321322| Reference | When to Load |323|-----------|-------------|324| `./references/type-system.md` | Advanced types, branded types, type-level programming, satisfies operator |325| `./references/generics-patterns.md` | Generic constraints, conditional types, mapped types, template literals, recursive types |326| `./references/utility-types.md` | All built-in utility types with examples, custom utility types |327| `./references/config-strict.md` | tsconfig deep dive, strict mode migration, project references, monorepo setup |328| `./references/ts7-native-compiler.md` | Adopting the TS 7 native (Go) compiler: no JS API, bin ambiguity, ecosystem lockout, benchmarked go/no-go |329| `./references/ecosystem.md` | Zod/Valibot, type-safe API clients, ORM types, testing with Vitest |330331## See Also332333- `testing-ops` - Cross-language testing strategies334- `ci-cd-ops` - TypeScript CI pipelines, type checking in CI