typescript-best-practices
Skill7 starsChanged 3 months agoMITView on GitHub
Idiomatic TypeScript conventions and best practices: strict compiler settings, type-level modeling (discriminated unions, branded/nominal types, `as const`/`satisfies`, exhaustiveness), `unknown` over `any`, immutability, error handling with a Result type, null/undefined hygiene, async/promise rules, module and naming conventions, and the project rule that every class exposes `toString()` and `toJSON()`. Use when writing new TypeScript, doing code review, setting up a tsconfig, modeling a domain type, or answering "what is the idiomatic TypeScript way to do this" questions. Ships ready-to- copy templates for value objects, entities, errors, Result, state machines, branded types, type guards, and a strict tsconfig.
77 other projects use a version of this.
Adopted by
Most recently taken up by
- Yeachan-Heo/oh-my-claude-sisyphustheir own version, first seen Nov 8, 2026
- caidanw/skillstheir own version, first seen Nov 8, 2026
- trpc/trpctheir own version, first seen Nov 8, 2026
- Yeachan-Heo/oh-my-claudecodetheir own version, first seen Nov 8, 2026
- endqwerty/endstacktheir own version, first seen Nov 8, 2026
- tristanphvn/keeltheir own version, first seen Nov 8, 2026
Used with
Projects with it also use setup-pstack, poteto-help and 10 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.
bnemaSkillsetup-pstack
Configure which Pi models pstack uses per role. Detects available provider/model specs and writes pstack's user configuration. Use for /setup-pstack, "configure pstack models", or changing pstack model choices.
Also in 22 projects that use this
ianclearySkillpoteto-help
Guides users through pstack setup, /poteto-mode, and picking the skill, playbook, or principle for a task. Type /poteto-help with a question.
Also in 12 projects that use this
eryzerzSkillmake-bot-ui
Use when building a custom UI (page, dashboard, buttons) that should wake a Grok Bot over a webhook, when the user must provide a webhook sender key, or when exposing that UI on Tailscale.
Also in 14 projects that use this
ianclearySkillprinciple-explain-the-number
Apply before you trust, report, or act on a number you measured: a speedup, a regression, a throughput, a latency, or an eval result. Find what limits it, and rule out that it measured something other than the work you think.
Also in 20 projects that use this
tristanphvnSkillketchup-video
Catch the user up like /keel:ketchup, with a short silent video of slides for what happened and the waiting calls as text under it. Use for /keel:ketchup-video.
Also in 8 projects that use this
instructureSkillketchup
Rebuild context after /clear by analyzing uncommitted changes across Canvas LMS and all plugin repositories
Also in 17 projects that use this
Other versions77 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 77
- trpc/trpc★ 41ksame name
- Yeachan-Heo/oh-my-claude-sisyphus★ 41ksame name
- Yeachan-Heo/oh-my-claudecode★ 41ksame name
- backnotprop/pstack★ 3.8ksame name
- jtaroreh/agystack★ 128same name
- uzairansaruzi/p3-stack★ 126same name
- dsebban/skills★ 71same name
- baekenough/oh-my-customcode★ 42same name
- overextended/skills★ 22same name
- TheOnlyFusionCube/potetos-for-everyone★ 21same name
67 more not listed
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 repository12 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- agent-teamsSkill
- bdd-specsSkill
- design-principlesSkill
- githubSkill
- gof-patternsSkill
- onboardSkill
- postgres-dbaSkill
- security-webSkill
- solid-principlesSkill
- sqlite-devSkill
- user-storiesSkill
The file
We split this skill into the rules it gives an agent
2 rules. 0 are common, 0 are distinctive, and 2 are very specific to this project.
0
Common
Most of the 26 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 119
No floating promises — await or explicit void.
- Very specific: line 120
Every class implements toString() and toJSON().
“Common” is measured: kept by at least 6 in 10 of the 26 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
TypeScript Best Practices & Idioms
How to write TypeScript that the compiler can actually protect: model
illegal states out of existence, prefer narrow types over any, make
invariants explicit, and keep runtime behavior (serialization, equality,
errors) predictable.
🎯 Why: Design for Change
The goal of writing software is to be able to change it safely. Strict
types, discriminated unions, branded types, and Result errors turn the
compiler into a change-detector: when a shape moves, every caller lights
up. any and loose types are change-hiders — they make the next edit
look safe while it isn't. Idiomatic TS exists to keep the next refactor
mechanical instead of archaeological.
This skill is about idioms and conventions. For OO design pressure use
solid-principles and design-principles; for named patterns use
gof-patterns. This skill does not re-explain those.
How to use this skill
- Match the symptom in the decision guide to a rule.
- Open
references/idioms.mdfor that rule's full rationale, a bad example, the idiomatic refactor, and when not to apply it. - Copy the closest file from
templates/and adapt it. The templates already encode the conventions below (strict types,toString/toJSON, exhaustiveness) so you start compliant instead of retrofitting. - Apply the smallest change that removes real pain. Strictness is earned
by demonstrated bugs, not applied as ceremony — but the defaults here
(strict tsconfig, no
any, no floating promises) are non-negotiable because their failure mode is silent.
Project rule: every class has toString() and toJSON()
This is a hard convention in this codebase, not a suggestion.
toJSON()— returns a plain, serializable object.JSON.stringifycalls it automatically, so logs, API responses, and persistence get a stable, intentional shape instead of leaking private fields, class internals, orundefined. Never return the instance itself.toString()— returns a short human-readable identifier for logs, error messages, and template literals (`order ${order}`). It is for humans;toJSON()is for machines. They are not interchangeable.
Why it is mandatory: without toJSON(), serialization is accidental — it
exposes whatever fields happen to be public today and breaks the moment a
private field is added. Without toString(), a class interpolated into a
string is [object Object], which destroys logs and error context. Both
methods make the class's external contract explicit and decoupled from
its internal representation (information hiding). See
references/tostring-tojson.md for the full rationale, edge cases
(circular refs, Date, bigint, secrets redaction), and the
copy-ready pattern. Every template in templates/ demonstrates it.
Decision guide
| Symptom / question | Rule | Where |
Reaching for any to silence the compiler | Use unknown + narrowing | idioms.md §1 |
enum Status { ... } | Use a string-literal union or as const object | idioms.md §2 |
| Object can be in contradictory states | Model with a discriminated union | idioms.md §3 |
Two string IDs got swapped at a call site | Brand the types (nominal) | idioms.md §4, templates/branded-type.ts |
switch silently misses a new case | Exhaustiveness check with never | idioms.md §5 |
| Config object loses literal types | as const + satisfies | idioms.md §6 |
| Throwing for an expected, recoverable failure | Return a Result<T, E> | idioms.md §7, templates/result.ts |
catch (e) then e.message | unknown catch + error narrowing | idioms.md §8, templates/app-error.ts |
| Mutable shared object mutated far away | readonly / Readonly<T> / freeze | idioms.md §9 |
null vs undefined used interchangeably | Pick one convention; ?./?? | idioms.md §10 |
| Floating promise / unhandled rejection | Always await; void deliberate fire-and-forget | idioms.md §11 |
Hand-written { id: ..., name: ... } derived from another type | Utility types (Pick/Omit/Partial) | idioms.md §12 |
| Validating external input by casting | Type guard / assertion function (or a schema lib) | idioms.md §13, templates/type-guards.ts |
| New class, modeling a domain value | Value object template | templates/value-object.ts |
| New class with identity/lifecycle | Entity template | templates/entity.ts |
interface vs type vs class indecision | Decision rule | idioms.md §14 |
Reference files
references/idioms.md— every rule above with motivation, a bad example, the idiomatic refactor, TypeScript-specific notes, and when the rule is over-engineering.references/tostring-tojson.md— the mandatorytoString/toJSONconvention in depth: contract, edge cases, redaction, testing.
Templates (copy and adapt)
| File | Use case |
templates/tsconfig.json | Strict baseline compiler config |
templates/value-object.ts | Immutable validated value (Money, Email) with factory, equals, toString/toJSON |
templates/entity.ts | Domain entity with identity, lifecycle, toString/toJSON |
templates/result.ts | Result<T, E> type + ok/err/map/unwrap helpers |
templates/app-error.ts | Typed error base class + subclasses, serializable, with toJSON/toString |
templates/discriminated-union.ts | State modeled as a tagged union with exhaustive handling |
templates/branded-type.ts | Zero-cost nominal types and smart constructors |
templates/type-guards.ts | User-defined type guards and assertion functions |
Non-negotiable defaults
These are silent-failure rules; apply them everywhere from day one:
strict: true(andnoUncheckedIndexedAccess) in tsconfig.- No
anyin committed code —unknown+ narrowing instead. - No floating promises —
awaitor explicitvoid. - Every class implements
toString()andtoJSON(). - Exported functions have explicit return types.
- External/untrusted data is validated at the boundary, never cast.
Does 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.

