TypeScript Advanced Patterns Best Practices
Type-level programming, library-author idioms, and feature-implementation patterns that go beyond surface uses of TypeScript 5.x. Contains 40 rules across 5 categories, prioritised by impact on consumer codebases.
When to Apply
Reference these guidelines when:
- Designing a public library or DSL surface (fluent builders, event emitters, route parsers, query builders, schema-derived clients)
- Writing type-level algorithms (recursive conditionals, accumulator pattern, key remapping, variadic tuples, type-level string/number ops, type-level tests)
- Using TS 5.x features in non-trivial ways (Stage 3 decorators,
usingcomposition,const Tfor overload disambiguation,NoInferfor anchor-vs-constrained parameters, variance annotations, the bivariance hole) - Encoding workflow state, transitions, and capabilities at the type level so illegal states and missing checks are compile errors
- Integrating with the declaration & module system (module augmentation, declaration merging, ambient asset modules, library type publishing via
exports/typesVersions)
Boundary with neighbouring skills
| Skill | Don't reach for this skill if you need… |
|---|---|
typescript (curated) | Compiler performance / tsconfig tuning |
typescript-refactor | General refactoring patterns and modern-TS surface basics |
ts-google | Google-style code style decisions |
clean-code-ts-react | Clean-code principles (naming, function shape, abstraction) |
effect-ts / opencode-ts | Effect library-specific patterns |
If a rule in this skill overlaps with one in typescript-refactor or .curated/typescript, the rule's Scope delta section names what this skill adds beyond the simpler version.
Rule Categories by Priority
| Priority | Category | Impact | Prefix | Rules |
|---|---|---|---|---|
| 1 | Library Author / DSL Patterns | CRITICAL | dsl- | 8 |
| 2 | Type-level Programming | HIGH | tlp- | 10 |
| 3 | Modern Features at Depth | HIGH | mod- | 8 |
| 4 | Feature Implementation Patterns | MEDIUM-HIGH | impl- | 8 |
| 5 | Declaration & Module System | MEDIUM | decl- | 6 |
Quick Reference
1. Library Author / DSL Patterns (CRITICAL)
dsl-fluent-builder-phantom-state— Enforce builder call order with phantom state typesdsl-typed-event-emitter— Build typed event emitters with mapped event mapsdsl-type-safe-object-paths— Type object path access with dot-notation inferencedsl-route-param-inference— Infer route parameters from path patternsdsl-schema-first-inference— Derive static types from runtime schemasdsl-type-safe-query-builder— Encode query shape in the builder's return typedsl-narrow-api-surface— Export only the API surface, not internal helpersdsl-overloads-vs-conditional-returns— Choose overloads over conditional return types
2. Type-level Programming (HIGH)
tlp-recursive-conditional-types— Use recursive conditional types for structural transformationstlp-tail-recursion-accumulator— Use tail-recursion accumulator pattern to bypass the 50-step limittlp-infer-extends-constraints— Constraininferwithextendsfor validated extractiontlp-key-remapping-as— Remap keys withasclauses in mapped typestlp-variadic-tuple-types— Use variadic tuples for position-aware type algorithmstlp-type-level-string-algorithms— Build type-level string algorithms with recursive template literalstlp-distributive-conditional-control— Control distribution with the[T] extends [U]tuple tricktlp-type-level-tests— Test types withEqual,Expect, and@ts-expect-errortlp-template-literal-pattern-matching— Match structured strings withinferin template literalstlp-hkt-emulation— Emulate higher-kinded types with interface dictionaries
3. Modern Features at Depth (HIGH)
mod-stage-3-decorators— Use Stage 3 decorators with decorator context for metaprogrammingmod-using-disposal-ordering— Composeusingresources with explicit disposal orderingmod-const-type-params-overloads— Useconst Tto preserve literals through overloaded APIsmod-noinfer-overload-disambiguation— UseNoInfer<T>to disambiguate overloaded function signaturesmod-variance-debugging— Debug variance errors within/outannotationsmod-method-vs-property-bivariance— Prefer property syntax over method syntax to avoid bivariance holesmod-phantom-capability-tracking— Track capabilities at the type level with phantom brandsmod-satisfies-branded-config— Combinesatisfieswith branded types for validated configuration
4. Feature Implementation Patterns (MEDIUM-HIGH)
impl-tagged-result-type— Model operation outcomes asOk<T> | Err<E>tagged unionsimpl-state-discriminated-union— Model workflow state as a discriminated union of state recordsimpl-finite-state-machine— Encode FSM transitions in function signaturesimpl-schema-derived-api-client— Derive client argument and return types from endpoint schemasimpl-type-safe-form-builder— Drive form-field inference from a single schema definitionimpl-phantom-feature-flags— Gate feature-dependent code with phantom capability typesimpl-assert-never-exhaustive— UseassertNeverto force exhaustive handling of union variantsimpl-env-config-loader— Validate environment configuration at boundary with schema inference
5. Declaration & Module System (MEDIUM)
decl-module-augmentation— Augment third-party module types without patching sourcedecl-declaration-merging— Merge interface, namespace, and class declarations to extend APIsdecl-ambient-asset-modules— Declare ambient modules for non-TypeScript asset importsdecl-global-augmentation-discipline— Scope global type augmentation to avoid conflictsdecl-exports-and-types-versions— Ship library types withexportsandtypesVersionsmapsdecl-authoring-d-ts-for-js— Author.d.tsfiles for plain JavaScript libraries
How to Use
Read individual reference files for detailed explanations, code examples, and "when NOT to apply" guidance:
- Section definitions — Category structure and impact levels
- Rule template — Template for adding new rules
Rules cross-link via [[other-rule-slug]]; follow them when a related pattern is referenced.
Reference Files
| File | Description |
|---|---|
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |