typescript-best-practices
Skill3 starsChanged 3 months agoMITView on GitHub
MUST USE when writing or editing TypeScript types, interfaces, generics, type guards, error handling patterns, or tsconfig configuration. Enforces TypeScript 7.x strict-mode best practices and type safety patterns.
- Installs packages
38 other projects use a version of this.
Adopted by
Most recently taken up by
- PickleBoxer/pstacktheir own version, first seen Oct 6, 2026
- uzairansaruzi/p3-stacktheir own version, first seen Oct 5, 2026
- backnotprop/pstacktheir own version, first seen Oct 4, 2026
- LuisUrrutia/skillstheir own version, first seen Oct 4, 2026
- creedants/pstack-t3their own version, first seen Oct 3, 2026
- baekenough/oh-my-customcodetheir own version, first seen Oct 3, 2026
Used with
Projects with it also use make-bot-ui, setup-pstack 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.
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 8 projects that use this
shishivSkillsetup-pstack
Configure pstack delegation against the active Pi host. Use for /skill:setup-pstack, "configure pstack models", or checking delegation readiness.
Also in 14 projects that use this
TheOnlyFusionCubeSkillprinciple-attack-the-premise
Inventory who actually owns or exhibits the imbalance, then challenge the shared premise before writing another patch. Use when two or more fixes that share one premise have failed the same gate.
Also in 10 projects that use this
TheOnlyFusionCubeSkillprinciple-test-behavior-not-implementation
Call the system the way its consumer does and assert meaningful observable output; avoid mocks or assertions that only mirror internal calls. Use when when writing or evaluating tests.
Also in 10 projects that use this
shishivSkillprinciple-never-block-on-the-human
Apply when tempted to ask 'should I do X?' on reversible work. Proceed, present the result, let the human course-correct after the fact; reserve confirmation for irreversible actions.
Also in 19 projects that use this
finograficSkillfigure-it-out
Design an auditable playbook when no narrower one fits: a large migration, an ambitious multi-part change, or work a human reviews after stepping away. Scales rigor to the task, runs a hypothesis loop, and logs decisions via show-me-your-work. Use for /figure-it-out, 'figure it out', a large migration, or when no narrower playbook applies.
Also in 20 projects that use this
- +6 more from shishiv
Other versions38 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 38
- backnotprop/pstack★ 991same name
- uzairansaruzi/p3-stack★ 129same name
- jtaroreh/agystack★ 58same name
- baekenough/oh-my-customcode★ 43same name
- shrimpwtf/oh-my-pstack★ 31same name
- korallis/skills-collection★ 18same name
- DavidTeju/shared-skills★ 9same name
- ofershap/typescript-best-practices★ 9same name
- flpbalada/fb-skills★ 8same name
- painhardcore/pstack★ 6same name
28 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 repository16 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- code-structureSkill
- debuggingSkill
- docker-best-practicesSkill
- drf-best-practicesSkill
- drizzle-ormSkill
- expressSkill
- fastapiSkill
- git-merge-conflictsSkill
- reactSkill
- researchSkill
- security-practicesSkill
- sqlSkill
- tanstack-querySkill
- tanstack-routerSkill
- testing-best-practicesSkill
The file
We split this skill into the rules it gives an agent
5 rules. 0 are common, 2 are distinctive, and 3 are very specific to this project.
0
Common
Most of the 14 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 290
Always: use unknown instead of any — narrow with type guards
- Distinctive: line 291
Always: use discriminated unions for multi-shape types
- Very specific: line 292
Always: use exhaustive never checks in switch statements
- Distinctive: line 295
Never: use numeric enums — use union types or const objects
- Very specific: line 296
Never: use type assertions (as) when a type guard is possible
“Common” is measured: kept by at least 6 in 10 of the 14 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 (TypeScript 7.x)
Type Design
Interface for objects, Type for everything else
// interface: extendable object shapes
interface Animal { name: string; }
interface Dog extends Animal { breed: string; }
// type: unions, intersections, computed types
type Result = Success | Failure;
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };Discriminated Unions over Optional Properties
// BAD: ambiguous states
interface Shape { kind: string; radius?: number; width?: number; height?: number; }
// GOOD: impossible states are unrepresentable
interface Circle { kind: "circle"; radius: number; }
interface Rectangle { kind: "rectangle"; width: number; height: number; }
type Shape = Circle | Rectangle;Branded Types
type Brand<T, B extends string> = T & { readonly __brand: B };
type UserId = Brand<string, "UserId">;
type ProductId = Brand<string, "ProductId">;
function getUser(id: UserId) {}
getUser(createProductId("prod_123")); // ERRORas const
const ROLES = ["admin", "user", "guest"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "user" | "guest"Utility Types
type UserPreview = Pick<User, "id" | "name">;
type CreateUserInput = Omit<User, "id" | "createdAt">;
type UpdateUserInput = Partial<Omit<User, "id">>;
type RolePermissions = Record<User["role"], string[]>;Type Safety
Avoid any — use unknown
// BAD
function parseJSON(json: string): any { return JSON.parse(json); }
// GOOD
function parseJSON(json: string): unknown { return JSON.parse(json); }
const data = parseJSON('{}');
if (typeof data === "object" && data !== null && "name" in data) {
console.log(data.name);
}Type Guards
// BAD: type assertion
const user = value as User;
// GOOD: type predicate
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null && "id" in value && "name" in value;
}
if (isUser(value)) console.log(value.name);
// GOOD: assertion function
function assertIsUser(value: unknown): asserts value is User {
if (!isUser(value)) throw new Error("Expected User");
}Exhaustive Checks with never
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
function getLabel(status: Status): string {
switch (status) {
case "pending": return "Pending";
case "active": return "Active";
case "archived": return "Archived";
default: return assertNever(status); // compile error if case missing
}
}satisfies — validate + preserve inference
// BAD: annotation widens, losing literal info
const colors: Record<string, string | [number, number, number]> = { red: [255, 0, 0], green: "#00ff00" };
colors.red.toUpperCase(); // ERROR
// GOOD
const colors = { red: [255, 0, 0], green: "#00ff00" } satisfies Record<string, string | [number, number, number]>;
colors.green.toUpperCase(); // OKas const satisfies — lock literals and validate
// Freezes literal types AND checks the shape — the idiom for config objects
const config = {
retries: 3,
mode: "strict",
} as const satisfies AppConfig;
config.mode; // type is "strict", not string — and the shape was checkedValidate External Data (Zod)
const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.string().email() });
type User = z.infer<typeof UserSchema>;
async function fetchUser(): Promise<User> {
const data = await fetch("/api/user").then(r => r.json());
return UserSchema.parse(data);
}Function Patterns
// Overloads: only when return type depends on input
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
// const type parameter: preserve literal inference without caller-side `as const`
function asTuple<const T extends readonly unknown[]>(t: T): T { return t; }
const pair = asTuple(["a", "b"]); // readonly ["a", "b"] — not string[]
// Parameter objects over long param lists
interface CreateUserParams { name: string; email: string; role: "admin" | "user"; }
function createUser(params: CreateUserParams) {}
// Infer return types internally, annotate on exports
export function fetchUsers(): Promise<User[]> { return api.get("/users"); }Type-Only Imports
With verbatimModuleSyntax (see tsconfig), imports used only as types must be marked type — they are erased from the JS output, preventing accidental runtime imports and breaking import cycles.
// GOOD: type-only import — erased at compile time
import type { User } from "./types";
// GOOD: inline `type` for a mixed import
import { type Role, createUser } from "./users";Resource Management — using
using (and await using) auto-dispose a resource when the scope exits, even on throw. The resource implements Symbol.dispose / Symbol.asyncDispose.
function openConn(url: string) {
const conn = connect(url);
return { conn, [Symbol.dispose]() { conn.close(); } };
}
function query() {
using db = openConn(DATABASE_URL); // db.conn.close() runs automatically
return db.conn.run("SELECT 1"); // ...even if this throws
}Common Pitfalls
Object.keys returns string[]
// GOOD: type-safe helper
function typedKeys<T extends object>(obj: T): (keyof T)[] {
return Object.keys(obj) as (keyof T)[];
}Array.filter needs type predicates
// BAD: doesn't narrow
const filtered = values.filter(v => v != null); // still (string | null)[]
// GOOD
function nonNullable<T>(value: T): value is NonNullable<T> { return value != null; }
const filtered = values.filter(nonNullable); // string[]Prefer unions over enums
// BAD: numeric enums accept any number
enum Direction { Up, Down }
move(99); // NO ERROR
// GOOD: union types
type Direction = "up" | "down" | "left" | "right";
// GOOD: const object when you need runtime values
const Status = { Active: "active", Inactive: "inactive" } as const;
type Status = (typeof Status)[keyof typeof Status];Error Handling — Result Pattern
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
function ok<T>(value: T): Result<T, never> { return { ok: true, value }; }
function err<E>(error: E): Result<never, E> { return { ok: false, error }; }
type AppError =
| { type: "NOT_FOUND"; resource: string }
| { type: "VALIDATION"; fields: string[] }
| { type: "UNAUTHORIZED"; reason: string };
async function fetchUser(id: string): Promise<Result<User, AppError>> {
const res = await fetch(`/api/users/${id}`);
if (res.status === 404) return err({ type: "NOT_FOUND", resource: "User" });
if (res.status === 401) return err({ type: "UNAUTHORIZED", reason: "Invalid token" });
return ok(UserSchema.parse(await res.json()));
}Recommended tsconfig.json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "bundler",
"isolatedModules": true,
"verbatimModuleSyntax": true,
"target": "ES2022",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"paths": { "@/*": ["./src/*"] }
}
}Under TypeScript 7.0 (current stable, GA July 8 2026), tsc is the native Go compiler — a plain npm i -D typescript installs it and type-checks ~10× faster; the old tsgo / @typescript/native-preview preview package is now just tsc. strict, module: "esnext", and a modern target are defaults — the block above keeps them explicit for clarity and older toolchains. moduleResolution values node / node10 / classic and baseUrl remain deprecated; paths works without baseUrl. Caveat: 7.0 ships no stable programmatic compiler API yet (lands in 7.1, ~Oct 2026), so editor tooling that depends on it — Vue / Svelte / Astro / Angular template type-checking — may need to stay on 6.x until then.
Rules
- Always enable
strict: trueandnoUncheckedIndexedAccess - Always use
unknowninstead ofany— narrow with type guards - Always use discriminated unions for multi-shape types
- Always use exhaustive
neverchecks in switch statements - Always validate external data at boundaries (Zod/valibot)
- Always annotate return types on exported functions
- Never use numeric enums — use union types or const objects
- Never use type assertions (
as) when a type guard is possible - Prefer
satisfiesover type annotations when you need both validation and inference - Prefer
as constfor literal arrays and config objects;as const satisfies Twhen you also need a shape check - Prefer
consttype parameters over caller-sideas constfor literal-preserving generics - Use
using/await usingfor resources that need deterministic cleanup - Mark type-only imports with
import type— required underverbatimModuleSyntax
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.

