typescript-advanced
Skill1 starsChanged 9 months agoApache-2.0View on GitHub
Advanced TypeScript patterns including branded/nominal types, discriminated unions with exhaustive matching, conditional types with infer, mapped types, template literal types, module augmentation, declaration merging, satisfies operator, const assertions, variance annotations, strict library authoring, and type-level programming. Use when writing complex type utilities, designing type-safe APIs, building shared libraries, or solving type inference problems.
- Reads credentials
5 other projects use a version of this.
Adopted by
Most recently taken up by
- compozy/compozytheir own version, first seen Oct 1, 2026
- FelipeAngeli/skillstheir own version, first seen Apr 10, 2026
- pedronauck/skillstheir own version, first seen Apr 3, 2026
- jander99/skillstheir own version, first seen Mar 15, 2026
- rohitg00/awesome-claude-code-toolkittheir own version, first seen Feb 4, 2026
Used with
Projects with it also use app-renderer-systems, refactoring-analysis and 6 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
pedronauckSkillapp-renderer-systems
Create, extend, or debug frontend domain modules organized under systems/. Covers adapters, Query hooks, local state, and public exports; excludes generic components and backend implementation.
Also in 3 projects that use this
pedronauckSkillrefactoring-analysis
Audit code quality and architectural health or plan refactoring using Fowler code smells and techniques; write prioritized findings to docs/_refacs/. Excludes formatting, performance, and security audits.
Also in 3 projects that use this
barisariburnuSkilltanstack
Expert assistance for TanStack Router, Query (v5), and Table (v8). Use when users need help with file-based routing, type-safe navigation, data loading, search params, queries, mutations, optimistic updates, infinite queries, table state management, or debugging TanStack libraries.
Also in 3 projects that use this
akornmeierSkilltailwindcss
Guide for implementing Tailwind CSS - a utility-first CSS framework for rapid UI development. Use when styling applications with responsive design, dark mode, custom themes, or building design systems with Tailwind's utility classes.
Also in 3 projects that use this
SentrySkillnext-best-practices
Next.js best practices - file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling
Also in 3 projects that use this
VercelSkillreact
React renderer for json-render that turns JSON specs into React components. Use when working with @json-render/react, building React UIs from JSON, creating component catalogs, or rendering AI-generated specs.
Also in 3 projects that use this
- +1 more from pedronauck
Other versions5 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 5
- compozy/compozy★ 2.8ksame name
- rohitg00/awesome-claude-code-toolkit★ 2.7ksame name
- pedronauck/skills★ 633same name
- FelipeAngeli/skills★ 2same name
- jander99/skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository73 other files it gives its agents.
- accessibility-wcagSkill
- api-designSkill
- api-testingSkill
- asset-optimizationSkill
- audio-systemsSkill
- aws-essentialsSkill
- ci-cd-pipelinesSkill
- codebase-analysisSkill
- code-reviewerSkill
- container-securitySkill
- cost-optimizationSkill
- database-designSkill
- data-visualizationSkill
- doc-generationSkill
- docker-kubernetesSkill
- docxSkill
- email-notificationsSkill
- env-configSkill
- flutter-mobileSkill
- framer-motionSkill
- frontend-code-reviewSkill
- frontend-designSkill
- fullstack-developerSkill
- game-enginesSkill
- gameplay-designSkill
- game-programming-languagesSkill
- game-serversSkill
- git-workflowSkill
- godot-4Skill
- golang-proSkill
- go-linter-configurationSkill
- graphics-renderingSkill
- i18n-localizationSkill
- incident-responseSkill
- level-designSkill
- llm-integrationSkill
- local-securitySkill
- memory-managementSkill
- monetization-systemsSkill
- monitoring-observabilitySkill
- multiplayer-netcodeSkill
- nextjs-16Skill
- notebooklm-researchSkill
- npm-packageSkill
- oauth-authSkill
- particle-systemsSkill
- performance-optimizationSkill
- playwright-testingSkill
- postgres-advancedSkill
- programming-architectureSkill
- project-migrationSkill
- publishing-platformsSkill
- python-best-practicesSkill
- react-nativeSkill
- redis-patternsSkill
- refactoring-patternsSkill
- remotion-best-practicesSkill
- rust-best-practicesSkill
- scraping-automationSkill
- security-reviewSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
11 rules. 0 are common, 4 are distinctive, and 7 are very specific to this project.
0
Common
Most of the 5 edited versions we read keep these.
4
Distinctive
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 55
Always use a literal type or kind field as the discriminant.
- Very specific: line 80
Use infer to extract types from generic positions.
- Distinctive: line 225
When you actually want widening (accepting any string, not just literals)
- Distinctive: line 226
When the type is already narrow enough (primitive types)
- Distinctive: line 227
When using with functions (use return type annotation instead)
- Very specific: line 282
When publishing types, prevent any leakage and ensure consumers get correct narrowing.
- Very specific: line 285
Never export any. Use unknown and force consumers to narrow.
- Very specific: line 286
Use readonly on all public array/object types.
- Very specific: line 287
Prefer interface for extendable shapes, type for closed unions.
- Distinctive: line 288
Add explicit return types on all public functions — inference leaks implementation details.
- Very specific: line 289
Test types with expectType from tsd or @ts-expect-error assertions.
“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
You are a senior TypeScript type-system engineer who writes zero-runtime-cost type safety and designs APIs where invalid states are unrepresentable.
Use this skill when
- Designing branded/nominal types to prevent value confusion (e.g., UserId vs OrderId)
- Building discriminated unions with exhaustive switch/match patterns
- Writing conditional types, mapped types, or template literal types
- Authoring shared libraries that must not leak
any - Using
satisfies,constassertions, or variance annotations - Solving complex type inference or type-level programming challenges
Branded and Nominal Types
TypeScript is structurally typed. Branded types add a phantom property to create nominal-like distinctions at zero runtime cost.
declare const __brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [__brand]: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
function createUserId(raw: string): UserId {
if (!raw.startsWith("usr_")) throw new Error("Invalid user ID");
return raw as UserId;
}
function getOrder(userId: UserId, orderId: OrderId): void {}
const uid = createUserId("usr_abc");
const oid = "ord_123" as OrderId;
// getOrder(oid, uid); // Compile error: argument types swappedFor numeric brands (prevent mixing pixels, milliseconds, etc.):
type Milliseconds = Brand<number, "Milliseconds">;
type Pixels = Brand<number, "Pixels">;
function delay(ms: Milliseconds): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
// delay(500); // Error: number is not Milliseconds
delay(500 as Milliseconds); // OK — explicit at call siteDiscriminated Unions and Exhaustive Matching
Always use a literal type or kind field as the discriminant. Enforce exhaustive handling with never.
interface LoadingState { readonly status: "loading" }
interface ErrorState { readonly status: "error"; readonly error: Error }
interface SuccessState<T> { readonly status: "success"; readonly data: T }
type AsyncState<T> = LoadingState | ErrorState | SuccessState<T>;
function assertNever(x: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(x)}`);
}
function render<T>(state: AsyncState<T>): string {
switch (state.status) {
case "loading": return "Loading...";
case "error": return `Error: ${state.error.message}`;
case "success": return `Data: ${JSON.stringify(state.data)}`;
default: return assertNever(state); // Compile error if a case is missing
}
}Conditional Types and infer
Use infer to extract types from generic positions. Think of it as pattern matching at the type level.
// Extract the resolved type from a Promise
type Awaited<T> = T extends Promise<infer U> ? Awaited<U> : T;
// Extract function return type (simplified ReturnType)
type Return<T> = T extends (...args: any[]) => infer R ? R : never;
// Extract array element type
type ElementOf<T> = T extends ReadonlyArray<infer E> ? E : never;
// Conditional distribution: filter union members
type ExtractString<T> = T extends string ? T : never;
type Result = ExtractString<string | number | boolean>; // string
// Prevent distribution with tuple wrapping
type NoDistribute<T> = [T] extends [string] ? "yes" : "no";
type Test = NoDistribute<string | number>; // "no" (evaluated as union, not distributed)Mapped Types
Transform object types property by property. Combine with key remapping (as) and template literals.
// Make all properties optional and nullable
type PartialNullable<T> = { [K in keyof T]?: T[K] | null };
// Create getters from an interface
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
interface User { name: string; age: number }
type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number }
// Filter keys by value type
type PickByType<T, U> = {
[K in keyof T as T[K] extends U ? K : never]: T[K];
};
type StringProps = PickByType<User, string>; // { name: string }Template Literal Types
Build type-safe string patterns without runtime checks.
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type ApiVersion = "v1" | "v2";
type Endpoint = `/${ApiVersion}/${string}`;
type EventName = `${"click" | "focus" | "blur"}${"" | `.${string}`}`;
// "click" | "focus" | "blur" | "click.foo" | "focus.bar" | ...
// Parse route params from a path string
type ExtractParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ExtractParams<Rest>
: T extends `${string}:${infer Param}`
? Param
: never;
type Params = ExtractParams<"/users/:userId/posts/:postId">;
// "userId" | "postId"satisfies Operator
Validates that an expression matches a type without widening it. Preserves the narrowest inferred type.
type Route = { path: string; exact?: boolean };
type Routes = Record<string, Route>;
// BAD: annotation widens — loses literal types
const routes: Routes = { home: { path: "/", exact: true } };
routes.home.path; // string (widened)
// GOOD: satisfies validates but keeps literals
const routes2 = {
home: { path: "/", exact: true },
about: { path: "/about" },
} satisfies Routes;
routes2.home.path; // "/" (literal preserved)
routes2.missing; // Compile error: property doesn't existDeep Dive: When to Use satisfies
Use satisfies when you want:
- Type validation at declaration without widening
- Autocomplete on object keys
- Literal type preservation for better type narrowing
// Example 1: Config with literal preservation
type Config = {
env: "development" | "staging" | "production";
features: Record<string, boolean>;
};
const config = {
env: "production",
features: { darkMode: true, beta: false },
} satisfies Config;
config.env; // "production" (literal), not string
// Example 2: Catch typos in object keys
type APIEndpoints = Record<"users" | "posts" | "comments", string>;
const endpoints = {
users: "/api/users",
posts: "/api/posts",
// comments: "/api/comments", // Missing — satisfies catches this
} satisfies APIEndpoints; // Error: missing "comments"
// Example 3: Discriminated union with exhaustiveness
type Status =
| { kind: "idle" }
| { kind: "loading"; progress: number }
| { kind: "error"; message: string };
const current = {
kind: "loading",
progress: 42,
} satisfies Status;
current.kind; // "loading" (literal), enables exhaustive switch
// Example 4: Combining with const assertion
const ROUTES = {
home: "/",
about: "/about",
contact: "/contact",
} as const satisfies Record<string, string>;
type RouteKeys = keyof typeof ROUTES; // "home" | "about" | "contact"
ROUTES.home; // "/" (literal string)When NOT to use satisfies:
- When you actually want widening (accepting any string, not just literals)
- When the type is already narrow enough (primitive types)
- When using with functions (use return type annotation instead)
const Assertions
Freeze literal types at declaration. Pairs with satisfies for validated readonly data.
const PERMISSIONS = ["read", "write", "admin"] as const;
type Permission = (typeof PERMISSIONS)[number]; // "read" | "write" | "admin"
const CONFIG = {
retries: 3,
timeout: 5000,
endpoints: ["https://a.com", "https://b.com"],
} as const satisfies { retries: number; timeout: number; endpoints: readonly string[] };
// CONFIG.retries is literal 3, not numberVariance Annotations (in, out)
Explicit variance on generics catches unsound assignments that structural typing misses. Use in library code.
interface Producer<out T> { get(): T }
interface Consumer<in T> { accept(value: T): void }
interface Invariant<in out T> { transform(value: T): T }
// Producer<Dog> assignable to Producer<Animal> (covariant) — OK
// Consumer<Animal> assignable to Consumer<Dog> (contravariant) — OK
// Invariant<Dog> NOT assignable to Invariant<Animal> — correctly blockedModule Augmentation and Declaration Merging
Extend third-party types without patching source. Interfaces with the same name merge automatically.
// Augment Express Request with custom properties
declare module "express-serve-static-core" {
interface Request {
userId?: string;
correlationId: string;
}
}
// Augment a library's enum-like namespace
declare module "@prisma/client" {
interface PrismaClient {
$metrics: { prometheus(): Promise<string> };
}
}Strict Library Authoring
When publishing types, prevent any leakage and ensure consumers get correct narrowing.
- Enable
strict,noUncheckedIndexedAccess,exactOptionalPropertyTypesin tsconfig. - Never export
any. Useunknownand force consumers to narrow. - Use
readonlyon all public array/object types. - Prefer
interfacefor extendable shapes,typefor closed unions. - Add explicit return types on all public functions — inference leaks implementation details.
- Test types with
expectTypefromtsdor@ts-expect-errorassertions.
// Type-level test: ensure an assignment fails
// @ts-expect-error — UserId should not accept raw string
const bad: UserId = "raw_string";Type-Level Programming Patterns
// Recursive type: deep partial
type DeepPartial<T> = T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
// Type-safe builder pattern
class QueryBuilder<Selected extends string = never> {
select<Col extends string>(col: Col): QueryBuilder<Selected | Col> {
return this as any; // runtime implementation
}
where(col: Selected, value: unknown): this { return this; }
}
new QueryBuilder()
.select("name")
.select("age")
.where("name", "Alice") // OK
// .where("email", "x") // Error: "email" not in SelectedDoes it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

