TypeScript Style Guide Skill
Activation: This skill activates whenever the user says or implies TypeScript. It responds
with standards-compliant TypeScript code and can explain any rule on demand.
Table of Contents
- General Principles
- Naming Conventions
- Types & Interfaces
- Enums
- Variables & Constants
- Functions
- Classes
- Modules & Imports
- Generics
- Error Handling
- Async / Await & Promises
- Comments & Documentation
- Formatting & Style
- Null & Undefined Handling
- Type Assertions & Guards
- React & JSX (when applicable)
- Testing Conventions
- Tooling & Configuration
1. General Principles
- Strict mode always: Enable
"strict": true in tsconfig.json. This turns on noImplicitAny,
strictNullChecks, strictFunctionTypes, and more.
- Prefer readability over cleverness: Code is read far more often than written. Favour explicit,
self-documenting code.
- Minimise
any: Treat every use of any as tech debt. Prefer unknown when the type is
truly not known, or use generics.
- Immutability by default: Use
const over let; prefer readonly properties and
ReadonlyArray<T> / Readonly<T> utility types.
- Single responsibility: Each file, class, and function should have one clear purpose.
- Keep files small: A file should ideally stay under 400 lines. If it grows larger, consider
splitting it.
2. Naming Conventions
| Construct |
Convention |
Example |
| Variable / Function |
camelCase |
getUserName, isActive |
| Boolean variable |
camelCase with prefix |
isLoading, hasAccess, canEdit |
| Constant (module) |
UPPER_SNAKE_CASE |
MAX_RETRY_COUNT, API_BASE_URL |
| Constant (local) |
camelCase |
const defaultTimeout = 3000 |
| Class |
PascalCase |
UserService, HttpClient |
| Interface |
PascalCase |
UserProfile, ApiResponse |
| Type alias |
PascalCase |
UserId, Theme |
| Enum |
PascalCase |
Direction, HttpStatus |
| Enum member |
PascalCase |
Direction.Up, HttpStatus.Ok |
| Generic parameter |
Single uppercase letter or descriptive PascalCase |
T, TKey, TValue |
| File name |
kebab-case.ts |
user-service.ts, api-client.ts |
| Test file name |
kebab-case.test.ts or kebab-case.spec.ts |
user-service.test.ts |
| React component file |
PascalCase.tsx |
UserProfile.tsx |
| Private field |
camelCase (no _ prefix) |
private count: number |
Additional Naming Rules
- Do NOT prefix interfaces with
I (e.g., IUser → User).
- Do NOT suffix types/interfaces with
Type or Interface.
- Use descriptive names. Avoid single-letter variables except for conventional usages like loop
indices (
i, j) or generic type parameters (T, K, V).
- Acronyms of 2 characters stay uppercase (
IO, ID); 3+ characters use PascalCase
(Http, Xml, Api).
3. Types & Interfaces
Prefer interface for Object Shapes
// ✅ Good — use interface for object shapes
interface User {
readonly id: string;
name: string;
email: string;
}
// ✅ Good — use type for unions, intersections, mapped types
type Status = 'active' | 'inactive' | 'suspended';
type Result<T> = Success<T> | Failure;
When to Use type vs interface
Use interface when … |
Use type when … |
| Defining the shape of an object or class |
Creating union or intersection types |
| You want declaration merging |
Using mapped / conditional types |
| Extending other interfaces |
Aliasing primitive or tuple types |
Rules
4. Enums
Prefer String Enums
// ✅ Good — string enum for readability and debuggability
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',
}
When to Use const Enum or Union Types
// ✅ Good — const enum for zero-runtime-cost enums (no reverse mapping needed)
const enum HttpMethod {
Get = 'GET',
Post = 'POST',
Put = 'PUT',
Delete = 'DELETE',
}
// ✅ Also good — string literal union (simpler, tree-shakeable)
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
Rules
- Do NOT use numeric enums without explicit values (auto-increment is fragile).
- Prefer string literal union types over enums when the set is small and no namespace features
are needed.
- Never mix string and numeric members in the same enum.
5. Variables & Constants
// ✅ Good
const maxRetries = 3;
const baseUrl = 'https://api.example.com';
let currentAttempt = 0;
// ❌ Bad — using var
var legacyValue = 'old';
// ❌ Bad — using let when value never changes
let neverReassigned = 42;
Rules
- Always use
const unless the variable needs reassignment; then use let.
- Never use
var.
- Declare variables as close to their first usage as possible.
- One variable declaration per statement.
- Prefer destructuring for extracting properties:
// ✅ Good
const { name, age } = user;
// ❌ Bad
const name = user.name;
const age = user.age;
- Use
as const for immutable literal objects / arrays:const ROUTES = {
home: '/',
about: '/about',
contact: '/contact',
} as const;
6. Functions
Function Declarations
// ✅ Good — explicit return type for public functions
function calculateTotal(items: CartItem[]): number {
return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
// ✅ Good — arrow function for callbacks / short lambdas
const double = (n: number): number => n * 2;
// ✅ Good — use default parameters instead of optional + fallback
function createUser(name: string, role: Role = Role.Viewer): User {
// ...
}
Rules
- Annotate return types for all exported / public functions.
- Prefer arrow functions for callbacks and inline functions.
- Prefer function declarations for top-level named functions (they are hoisted and more
readable in stack traces).
- Maximum parameters: 3. If more are needed, group them into an options object:
// ✅ Good
interface CreateUserOptions {
name: string;
email: string;
role?: Role;
department?: string;
}
function createUser(options: CreateUserOptions): User { ... }
// ❌ Bad — too many positional parameters
function createUser(name: string, email: string, role: Role, dept: string): User { ... }
- Do not use
arguments; use rest parameters (...args) instead.
- Avoid
Function type. Use specific function signatures.
- Keep functions small — ideally under 30 lines of logic.
- Functions should do one thing.
- Prefer early returns to reduce nesting:
// ✅ Good
function getDiscount(user: User): number {
if (!user.isPremium) return 0;
if (user.yearsActive < 2) return 5;
return 10;
}
7. Classes
// ✅ Good
class UserService {
private readonly repository: UserRepository;
constructor(repository: UserRepository) {
this.repository = repository;
}
async findById(id: string): Promise<User | undefined> {
return this.repository.get(id);
}
}
Rules
8. Modules & Imports
// ✅ Good — named exports
export function parseConfig(raw: string): Config { ... }
export interface Config { ... }
// ✅ Good — re-export barrel file (index.ts)
export { parseConfig } from './parse-config';
export type { Config } from './parse-config';
Rules
9. Generics
// ✅ Good — descriptive when intent is ambiguous
function merge<TTarget, TSource>(target: TTarget, source: TSource): TTarget & TSource {
return { ...target, ...source };
}
// ✅ Good — single-letter when intent is obvious
function identity<T>(value: T): T {
return value;
}
// ✅ Good — constrained generics
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Rules
- Use a single uppercase letter (
T, U, K, V) for simple generics.
- Use descriptive PascalCase prefixed with
T (TKey, TValue, TResult) when there are
multiple type parameters or the purpose is not obvious.
- Always add constraints when possible (
<T extends SomeType>).
- Avoid unnecessary generics — if a type parameter is used only once, it's likely not needed.
- Prefer generic utility types (
Array<T>, Promise<T>, Map<K, V>) over their shorthand where
readability benefits.
10. Error Handling
// ✅ Good — custom error class
class AppError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly statusCode: number = 500,
) {
super(message);
this.name = 'AppError';
}
}
// ✅ Good — typed error handling
function parseJson<T>(raw: string): T {
try {
return JSON.parse(raw) as T;
} catch (error) {
throw new AppError(
`Failed to parse JSON: ${error instanceof Error ? error.message : String(error)}`,
'PARSE_ERROR',
400,
);
}
}
Rules
11. Async / Await & Promises
// ✅ Good — async/await
async function fetchUser(id: string): Promise<User> {
const response = await httpClient.get<User>(`/users/${id}`);
return response.data;
}
// ✅ Good — parallel execution
async function fetchDashboard(userId: string): Promise<Dashboard> {
const [user, posts, notifications] = await Promise.all([
fetchUser(userId),
fetchPosts(userId),
fetchNotifications(userId),
]);
return { user, posts, notifications };
}
Rules
- Prefer
async/await over .then() chains for readability.
- Always annotate return types as
Promise<T>.
- Use
Promise.all() for independent concurrent operations.
- Use
Promise.allSettled() when failures should not abort sibling operations.
- Never use
new Promise() when an async function suffices (avoid the explicit-construction
antipattern).
- Avoid
async void functions — they cannot be await-ed and swallow errors.
Exception: event handlers where the framework requires void.
- Prefer
for...of with await for sequential async iteration, not forEach.
12. Comments & Documentation
/**
* Calculate the compound interest for a principal amount.
*
* @param principal - The initial amount of money.
* @param rate - The annual interest rate (decimal, e.g. 0.05 for 5%).
* @param times - Number of times interest is compounded per year.
* @param years - Number of years the money is invested.
* @returns The total amount after compound interest.
*
* @example
* ```typescript
* const total = compoundInterest(1000, 0.05, 12, 10);
* // total ≈ 1647.01
* ```
*/
function compoundInterest(
principal: number,
rate: number,
times: number,
years: number,
): number {
return principal * Math.pow(1 + rate / times, times * years);
}
Rules
- Use TSDoc (
/** */) for all public APIs, exported functions, classes, interfaces, and types.
- Include
@param, @returns, @throws, and @example tags where applicable.
- Do NOT comment obvious code. The code should be self-documenting.
- Use
// TODO: with a ticket number for planned improvements.
- Use
// FIXME: for known issues that need resolution.
- Use
// HACK: for workarounds that should be revisited.
- Never leave commented-out code in the main branch.
- Place file-level comments at the top if the module's purpose is not obvious from its name.
- Keep comments up-to-date with code changes.
13. Formatting & Style
General
- Indentation: 2 spaces (no tabs).
- Semicolons: Required at the end of every statement.
- Quotes: Single quotes (
') for strings; backticks (`) for template literals.
- Trailing commas: Always use in multi-line constructs (arrays, objects, parameters, generics).
- Max line length: 100 characters (soft limit), 120 characters (hard limit).
- Braces: Required for all control structures, even single-line bodies.
- Blank lines: One blank line between top-level declarations; no multiple consecutive blank lines.
Specific Patterns
// ✅ Good — braces always, even for single-line if
if (isValid) {
process();
}
// ❌ Bad
if (isValid) process();
// ✅ Good — trailing comma
const config = {
host: 'localhost',
port: 3000,
debug: true,
};
// ✅ Good — consistent object shorthand
const name = 'Alice';
const user = { name, age: 30 };
Tooling
- Use Prettier for auto-formatting with the following baseline config:
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"arrowParens": "always"
}
- Use ESLint with
@typescript-eslint/eslint-plugin and
@typescript-eslint/parser for linting.
14. Null & Undefined Handling
// ✅ Good — optional chaining
const city = user?.address?.city;
// ✅ Good — nullish coalescing
const displayName = user.nickname ?? user.name ?? 'Anonymous';
// ✅ Good — explicit null checks for critical paths
function getUser(id: string): User {
const user = repository.findById(id);
if (user === undefined) {
throw new AppError(`User not found: ${id}`, 'USER_NOT_FOUND', 404);
}
return user;
}
Rules
- Enable
strictNullChecks (included in strict mode).
- Prefer
undefined over null as the "absence of value" indicator, unless interacting with
external APIs that use null.
- Use optional chaining (
?.) and nullish coalescing (??) instead of manual checks.
- Do NOT use non-null assertion (
!) unless you can prove the value is always defined (add a
comment explaining why).
- Prefer the
satisfies operator (TS 5.0+) to validate types without widening.
15. Type Assertions & Guards
// ✅ Good — type guard function
function isUser(value: unknown): value is User {
return (
typeof value === 'object' &&
value !== null &&
'id' in value &&
'name' in value
);
}
// ✅ Good — discriminated union
interface Success<T> {
kind: 'success';
data: T;
}
interface Failure {
kind: 'failure';
error: Error;
}
type Result<T> = Success<T> | Failure;
function handleResult<T>(result: Result<T>): T {
switch (result.kind) {
case 'success':
return result.data;
case 'failure':
throw result.error;
}
}
Rules
- Prefer type guards (
is keyword) over type assertions (as).
- Use
as const for literal narrowing, not as SpecificType.
- Use discriminated unions with a
kind / type field for state machines and result types.
- Avoid
as unknown as T double assertions — they are almost always a design smell.
- When assertions are necessary, add a comment justifying them.
- Use
satisfies for type validation without assertion:const palette = {
red: [255, 0, 0],
green: '#00ff00',
} satisfies Record<string, string | number[]>;
16. React & JSX (when applicable)
// ✅ Good — functional component with explicit props type
interface UserCardProps {
readonly user: User;
readonly onSelect?: (userId: string) => void;
}
export function UserCard({ user, onSelect }: UserCardProps): React.ReactElement {
const handleClick = useCallback(() => {
onSelect?.(user.id);
}, [onSelect, user.id]);
return (
<div className="user-card" role="button" tabIndex={0}>
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
);
}
Rules
- Use function declarations or named function expressions for components (not anonymous).
- Define props as an
interface (e.g., UserCardProps), not inline.
- Mark all props as
readonly.
- Do NOT use
React.FC — it is discouraged since React 18.
- Use
React.ReactElement or React.ReactNode as return type annotation.
- Colocate styles, tests, and types with the component when practical.
- Prefer controlled components over uncontrolled.
- Memoize expensive computations with
useMemo, stable callbacks with useCallback.
- Extract custom hooks when logic is reused across components.
- Component file structure:
- Imports
- Types / Interfaces
- Constants
- Component function
- Helper functions (private to the module)
17. Testing Conventions
// ✅ Good — descriptive test structure
describe('UserService', () => {
describe('findById', () => {
it('should return the user when the id exists', async () => {
const user = await service.findById('user-1');
expect(user).toEqual(expect.objectContaining({ id: 'user-1' }));
});
it('should return undefined when the id does not exist', async () => {
const user = await service.findById('non-existent');
expect(user).toBeUndefined();
});
});
});
Rules
18. Tooling & Configuration
Recommended tsconfig.json (Baseline)
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
}
Recommended ESLint Rules
| Rule |
Setting |
@typescript-eslint/no-explicit-any |
error |
@typescript-eslint/explicit-function-return-type |
warn (for exported functions) |
@typescript-eslint/no-unused-vars |
error |
@typescript-eslint/consistent-type-imports |
error |
@typescript-eslint/no-non-null-assertion |
warn |
@typescript-eslint/prefer-nullish-coalescing |
error |
@typescript-eslint/prefer-optional-chain |
error |
@typescript-eslint/strict-boolean-expressions |
warn |
@typescript-eslint/naming-convention |
error (configured per construct) |
Usage
Natural Language Activation
Simply mention TypeScript in your conversation — the skill activates automatically.
Example prompts:
| Prompt |
Skill Response |
| "Write a TypeScript function to merge two objects deeply" |
Generates a fully typed, standards-compliant deepMerge<T, U>() function following all rules above. |
| "Review my TypeScript code for style issues" |
Analyses the provided code against this guide and suggests improvements. |
| "Convert this JavaScript to TypeScript" |
Converts code, adds strict types, interfaces, and follows all naming / formatting conventions. |
| "What's the TypeScript best practice for error handling?" |
Explains the Result pattern, custom error classes, and typed catch blocks per §10. |
| "Create a TypeScript React component for a data table" |
Generates a well-typed functional component following §16 React rules with proper props interface. |
| "Set up a new TypeScript project" |
Provides tsconfig.json, ESLint config, Prettier config, and project structure following §18. |
Inline Rule References
You can ask about any specific section:
- "Explain TypeScript naming conventions" → References §2
- "How should I handle null in TypeScript?" → References §14
- "Show me TypeScript generic best practices" → References §9
1---2name: typescript3slug: typescript4license: MIT5description: >6 Provide best-practice coding conventions and generate standards-compliant7 TypeScript code.8metadata:9 source: https://skillmd.com/skills/leoyeai-openclaw-master-skills/typescript10---1112# TypeScript Style Guide Skill1314> **Activation**: This skill activates whenever the user says or implies **TypeScript**. It responds15> with standards-compliant TypeScript code and can explain any rule on demand.1617---1819## Table of Contents20211. [General Principles](#1-general-principles)222. [Naming Conventions](#2-naming-conventions)233. [Types & Interfaces](#3-types--interfaces)244. [Enums](#4-enums)255. [Variables & Constants](#5-variables--constants)266. [Functions](#6-functions)277. [Classes](#7-classes)288. [Modules & Imports](#8-modules--imports)299. [Generics](#9-generics)3010. [Error Handling](#10-error-handling)3111. [Async / Await & Promises](#11-async--await--promises)3212. [Comments & Documentation](#12-comments--documentation)3313. [Formatting & Style](#13-formatting--style)3414. [Null & Undefined Handling](#14-null--undefined-handling)3515. [Type Assertions & Guards](#15-type-assertions--guards)3616. [React & JSX (when applicable)](#16-react--jsx-when-applicable)3717. [Testing Conventions](#17-testing-conventions)3818. [Tooling & Configuration](#18-tooling--configuration)3940---4142## 1. General Principles4344- **Strict mode always**: Enable `"strict": true` in `tsconfig.json`. This turns on `noImplicitAny`,45 `strictNullChecks`, `strictFunctionTypes`, and more.46- **Prefer readability over cleverness**: Code is read far more often than written. Favour explicit,47 self-documenting code.48- **Minimise `any`**: Treat every use of `any` as tech debt. Prefer `unknown` when the type is49 truly not known, or use generics.50- **Immutability by default**: Use `const` over `let`; prefer `readonly` properties and51 `ReadonlyArray<T>` / `Readonly<T>` utility types.52- **Single responsibility**: Each file, class, and function should have one clear purpose.53- **Keep files small**: A file should ideally stay under 400 lines. If it grows larger, consider54 splitting it.5556---5758## 2. Naming Conventions5960| Construct | Convention | Example |61| ----------------------- | ----------------------- | -------------------------------- |62| **Variable / Function** | `camelCase` | `getUserName`, `isActive` |63| **Boolean variable** | `camelCase` with prefix | `isLoading`, `hasAccess`, `canEdit` |64| **Constant (module)** | `UPPER_SNAKE_CASE` | `MAX_RETRY_COUNT`, `API_BASE_URL`|65| **Constant (local)** | `camelCase` | `const defaultTimeout = 3000` |66| **Class** | `PascalCase` | `UserService`, `HttpClient` |67| **Interface** | `PascalCase` | `UserProfile`, `ApiResponse` |68| **Type alias** | `PascalCase` | `UserId`, `Theme` |69| **Enum** | `PascalCase` | `Direction`, `HttpStatus` |70| **Enum member** | `PascalCase` | `Direction.Up`, `HttpStatus.Ok` |71| **Generic parameter** | Single uppercase letter or descriptive `PascalCase` | `T`, `TKey`, `TValue` |72| **File name** | `kebab-case.ts` | `user-service.ts`, `api-client.ts`|73| **Test file name** | `kebab-case.test.ts` or `kebab-case.spec.ts` | `user-service.test.ts` |74| **React component file**| `PascalCase.tsx` | `UserProfile.tsx` |75| **Private field** | `camelCase` (no `_` prefix) | `private count: number` |7677### Additional Naming Rules7879- **Do NOT** prefix interfaces with `I` (e.g., ~~`IUser`~~ → `User`).80- **Do NOT** suffix types/interfaces with `Type` or `Interface`.81- Use descriptive names. Avoid single-letter variables except for conventional usages like loop82 indices (`i`, `j`) or generic type parameters (`T`, `K`, `V`).83- Acronyms of 2 characters stay uppercase (`IO`, `ID`); 3+ characters use PascalCase84 (`Http`, `Xml`, `Api`).8586---8788## 3. Types & Interfaces8990### Prefer `interface` for Object Shapes9192```typescript93// ✅ Good — use interface for object shapes94interface User {95 readonly id: string;96 name: string;97 email: string;98}99100// ✅ Good — use type for unions, intersections, mapped types101type Status = 'active' | 'inactive' | 'suspended';102type Result<T> = Success<T> | Failure;103```104105### When to Use `type` vs `interface`106107| Use `interface` when … | Use `type` when … |108| ---------------------------------------------- | ------------------------------------------ |109| Defining the shape of an object or class | Creating union or intersection types |110| You want declaration merging | Using mapped / conditional types |111| Extending other interfaces | Aliasing primitive or tuple types |112113### Rules114115- Always annotate function return types explicitly for public APIs.116- Let TypeScript infer types for local variables when the type is obvious.117- Prefer `type` over `interface` for function signatures:118 ```typescript119 type Comparator<T> = (a: T, b: T) => number;120 ```121- Avoid empty interfaces. If extending, include at least a comment explaining intent.122- Use `Record<K, V>` instead of `{ [key: string]: V }`.123- Use utility types (`Partial<T>`, `Pick<T, K>`, `Omit<T, K>`, `Required<T>`) to derive types124 rather than duplicating.125126---127128## 4. Enums129130### Prefer String Enums131132```typescript133// ✅ Good — string enum for readability and debuggability134enum Direction {135 Up = 'UP',136 Down = 'DOWN',137 Left = 'LEFT',138 Right = 'RIGHT',139}140```141142### When to Use `const` Enum or Union Types143144```typescript145// ✅ Good — const enum for zero-runtime-cost enums (no reverse mapping needed)146const enum HttpMethod {147 Get = 'GET',148 Post = 'POST',149 Put = 'PUT',150 Delete = 'DELETE',151}152153// ✅ Also good — string literal union (simpler, tree-shakeable)154type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';155```156157### Rules158159- **Do NOT** use numeric enums without explicit values (auto-increment is fragile).160- Prefer **string literal union types** over enums when the set is small and no namespace features161 are needed.162- Never mix string and numeric members in the same enum.163164---165166## 5. Variables & Constants167168```typescript169// ✅ Good170const maxRetries = 3;171const baseUrl = 'https://api.example.com';172let currentAttempt = 0;173174// ❌ Bad — using var175var legacyValue = 'old';176177// ❌ Bad — using let when value never changes178let neverReassigned = 42;179```180181### Rules182183- **Always use `const`** unless the variable needs reassignment; then use `let`.184- **Never use `var`**.185- Declare variables as close to their first usage as possible.186- One variable declaration per statement.187- Prefer destructuring for extracting properties:188 ```typescript189 // ✅ Good190 const { name, age } = user;191192 // ❌ Bad193 const name = user.name;194 const age = user.age;195 ```196- Use `as const` for immutable literal objects / arrays:197 ```typescript198 const ROUTES = {199 home: '/',200 about: '/about',201 contact: '/contact',202 } as const;203 ```204205---206207## 6. Functions208209### Function Declarations210211```typescript212// ✅ Good — explicit return type for public functions213function calculateTotal(items: CartItem[]): number {214 return items.reduce((sum, item) => sum + item.price * item.quantity, 0);215}216217// ✅ Good — arrow function for callbacks / short lambdas218const double = (n: number): number => n * 2;219220// ✅ Good — use default parameters instead of optional + fallback221function createUser(name: string, role: Role = Role.Viewer): User {222 // ...223}224```225226### Rules227228- **Annotate return types** for all exported / public functions.229- Prefer **arrow functions** for callbacks and inline functions.230- Prefer **function declarations** for top-level named functions (they are hoisted and more231 readable in stack traces).232- **Maximum parameters**: 3. If more are needed, group them into an options object:233 ```typescript234 // ✅ Good235 interface CreateUserOptions {236 name: string;237 email: string;238 role?: Role;239 department?: string;240 }241 function createUser(options: CreateUserOptions): User { ... }242243 // ❌ Bad — too many positional parameters244 function createUser(name: string, email: string, role: Role, dept: string): User { ... }245 ```246- Do **not** use `arguments`; use rest parameters (`...args`) instead.247- Avoid `Function` type. Use specific function signatures.248- Keep functions small — ideally under 30 lines of logic.249- Functions should **do one thing**.250- Prefer **early returns** to reduce nesting:251 ```typescript252 // ✅ Good253 function getDiscount(user: User): number {254 if (!user.isPremium) return 0;255 if (user.yearsActive < 2) return 5;256 return 10;257 }258 ```259260---261262## 7. Classes263264```typescript265// ✅ Good266class UserService {267 private readonly repository: UserRepository;268269 constructor(repository: UserRepository) {270 this.repository = repository;271 }272273 async findById(id: string): Promise<User | undefined> {274 return this.repository.get(id);275 }276}277```278279### Rules280281- Prefer **composition over inheritance**.282- Use `readonly` for properties that should not change after construction.283- Member ordering:284 1. Static fields285 2. Instance fields286 3. Constructor287 4. Static methods288 5. Public methods289 6. Protected methods290 7. Private methods291- Use **explicit access modifiers** (`public`, `protected`, `private`) on every member.292- **Do NOT** prefix private members with `_`. TypeScript's `private` keyword is sufficient.293- Use `#` (ES private fields) when true runtime privacy is required.294- Prefer **parameter properties** for simple constructor-only assignments:295 ```typescript296 class Logger {297 constructor(private readonly prefix: string) {}298 }299 ```300- Avoid classes with only static methods — use plain functions in a module instead.301- Implement interfaces explicitly:302 ```typescript303 class UserRepositoryImpl implements UserRepository { ... }304 ```305306---307308## 8. Modules & Imports309310```typescript311// ✅ Good — named exports312export function parseConfig(raw: string): Config { ... }313export interface Config { ... }314315// ✅ Good — re-export barrel file (index.ts)316export { parseConfig } from './parse-config';317export type { Config } from './parse-config';318```319320### Rules321322- **Prefer named exports** over default exports (better refactoring, auto-import support).323- Use default exports only for React components if the project convention requires it.324- Use `import type` / `export type` for type-only imports to help bundlers tree-shake:325 ```typescript326 import type { User } from './user';327 ```328- Group and order imports:329 1. Node built-ins (`node:fs`, `node:path`)330 2. External packages (`react`, `lodash`)331 3. Internal aliases (`@/utils`, `@/components`)332 4. Relative parent (`../`)333 5. Relative sibling (`./`)334- Separate each group with a blank line.335- **Do NOT** use wildcard imports (`import * as`) unless re-exporting a module namespace.336- Keep barrel files (`index.ts`) thin — do not add logic.337338---339340## 9. Generics341342```typescript343// ✅ Good — descriptive when intent is ambiguous344function merge<TTarget, TSource>(target: TTarget, source: TSource): TTarget & TSource {345 return { ...target, ...source };346}347348// ✅ Good — single-letter when intent is obvious349function identity<T>(value: T): T {350 return value;351}352353// ✅ Good — constrained generics354function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {355 return obj[key];356}357```358359### Rules360361- Use a **single uppercase letter** (`T`, `U`, `K`, `V`) for simple generics.362- Use **descriptive PascalCase prefixed with `T`** (`TKey`, `TValue`, `TResult`) when there are363 multiple type parameters or the purpose is not obvious.364- Always add constraints when possible (`<T extends SomeType>`).365- Avoid unnecessary generics — if a type parameter is used only once, it's likely not needed.366- Prefer generic utility types (`Array<T>`, `Promise<T>`, `Map<K, V>`) over their shorthand where367 readability benefits.368369---370371## 10. Error Handling372373```typescript374// ✅ Good — custom error class375class AppError extends Error {376 constructor(377 message: string,378 public readonly code: string,379 public readonly statusCode: number = 500,380 ) {381 super(message);382 this.name = 'AppError';383 }384}385386// ✅ Good — typed error handling387function parseJson<T>(raw: string): T {388 try {389 return JSON.parse(raw) as T;390 } catch (error) {391 throw new AppError(392 `Failed to parse JSON: ${error instanceof Error ? error.message : String(error)}`,393 'PARSE_ERROR',394 400,395 );396 }397}398```399400### Rules401402- **Never** swallow errors silently (empty `catch` blocks).403- Use **custom error classes** that extend `Error` for domain-specific errors.404- Type the `catch` variable as `unknown` (default in TS 4.4+) and narrow before use.405- Prefer **Result / Either patterns** for expected failures in libraries:406 ```typescript407 type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };408 ```409- Always clean up resources in `finally` blocks or use disposable patterns.410- Log errors with sufficient context (operation name, input summary, stack trace).411412---413414## 11. Async / Await & Promises415416```typescript417// ✅ Good — async/await418async function fetchUser(id: string): Promise<User> {419 const response = await httpClient.get<User>(`/users/${id}`);420 return response.data;421}422423// ✅ Good — parallel execution424async function fetchDashboard(userId: string): Promise<Dashboard> {425 const [user, posts, notifications] = await Promise.all([426 fetchUser(userId),427 fetchPosts(userId),428 fetchNotifications(userId),429 ]);430 return { user, posts, notifications };431}432```433434### Rules435436- **Prefer `async/await`** over `.then()` chains for readability.437- Always annotate return types as `Promise<T>`.438- Use `Promise.all()` for independent concurrent operations.439- Use `Promise.allSettled()` when failures should not abort sibling operations.440- **Never** use `new Promise()` when an async function suffices (avoid the explicit-construction441 antipattern).442- Avoid `async void` functions — they cannot be `await`-ed and swallow errors.443 Exception: event handlers where the framework requires `void`.444- Prefer `for...of` with `await` for sequential async iteration, not `forEach`.445446---447448## 12. Comments & Documentation449450```typescript451/**452 * Calculate the compound interest for a principal amount.453 *454 * @param principal - The initial amount of money.455 * @param rate - The annual interest rate (decimal, e.g. 0.05 for 5%).456 * @param times - Number of times interest is compounded per year.457 * @param years - Number of years the money is invested.458 * @returns The total amount after compound interest.459 *460 * @example461 * ```typescript462 * const total = compoundInterest(1000, 0.05, 12, 10);463 * // total ≈ 1647.01464 * ```465 */466function compoundInterest(467 principal: number,468 rate: number,469 times: number,470 years: number,471): number {472 return principal * Math.pow(1 + rate / times, times * years);473}474```475476### Rules477478- Use **TSDoc** (`/** */`) for all public APIs, exported functions, classes, interfaces, and types.479- Include `@param`, `@returns`, `@throws`, and `@example` tags where applicable.480- **Do NOT** comment obvious code. The code should be self-documenting.481- Use `// TODO:` with a ticket number for planned improvements.482- Use `// FIXME:` for known issues that need resolution.483- Use `// HACK:` for workarounds that should be revisited.484- Never leave commented-out code in the main branch.485- Place file-level comments at the top if the module's purpose is not obvious from its name.486- Keep comments up-to-date with code changes.487488---489490## 13. Formatting & Style491492### General493494- **Indentation**: 2 spaces (no tabs).495- **Semicolons**: Required at the end of every statement.496- **Quotes**: Single quotes (`'`) for strings; backticks (`` ` ``) for template literals.497- **Trailing commas**: Always use in multi-line constructs (arrays, objects, parameters, generics).498- **Max line length**: 100 characters (soft limit), 120 characters (hard limit).499- **Braces**: Required for all control structures, even single-line bodies.500- **Blank lines**: One blank line between top-level declarations; no multiple consecutive blank lines.501502### Specific Patterns503504```typescript505// ✅ Good — braces always, even for single-line if506if (isValid) {507 process();508}509510// ❌ Bad511if (isValid) process();512513// ✅ Good — trailing comma514const config = {515 host: 'localhost',516 port: 3000,517 debug: true,518};519520// ✅ Good — consistent object shorthand521const name = 'Alice';522const user = { name, age: 30 };523```524525### Tooling526527- Use **Prettier** for auto-formatting with the following baseline config:528 ```json529 {530 "semi": true,531 "singleQuote": true,532 "trailingComma": "all",533 "printWidth": 100,534 "tabWidth": 2,535 "arrowParens": "always"536 }537 ```538- Use **ESLint** with `@typescript-eslint/eslint-plugin` and539 `@typescript-eslint/parser` for linting.540541---542543## 14. Null & Undefined Handling544545```typescript546// ✅ Good — optional chaining547const city = user?.address?.city;548549// ✅ Good — nullish coalescing550const displayName = user.nickname ?? user.name ?? 'Anonymous';551552// ✅ Good — explicit null checks for critical paths553function getUser(id: string): User {554 const user = repository.findById(id);555 if (user === undefined) {556 throw new AppError(`User not found: ${id}`, 'USER_NOT_FOUND', 404);557 }558 return user;559}560```561562### Rules563564- **Enable `strictNullChecks`** (included in `strict` mode).565- Prefer `undefined` over `null` as the "absence of value" indicator, unless interacting with566 external APIs that use `null`.567- Use **optional chaining** (`?.`) and **nullish coalescing** (`??`) instead of manual checks.568- **Do NOT** use non-null assertion (`!`) unless you can prove the value is always defined (add a569 comment explaining why).570- Prefer the `satisfies` operator (TS 5.0+) to validate types without widening.571572---573574## 15. Type Assertions & Guards575576```typescript577// ✅ Good — type guard function578function isUser(value: unknown): value is User {579 return (580 typeof value === 'object' &&581 value !== null &&582 'id' in value &&583 'name' in value584 );585}586587// ✅ Good — discriminated union588interface Success<T> {589 kind: 'success';590 data: T;591}592interface Failure {593 kind: 'failure';594 error: Error;595}596type Result<T> = Success<T> | Failure;597598function handleResult<T>(result: Result<T>): T {599 switch (result.kind) {600 case 'success':601 return result.data;602 case 'failure':603 throw result.error;604 }605}606```607608### Rules609610- **Prefer type guards** (`is` keyword) over type assertions (`as`).611- Use `as const` for literal narrowing, not `as SpecificType`.612- Use **discriminated unions** with a `kind` / `type` field for state machines and result types.613- Avoid `as unknown as T` double assertions — they are almost always a design smell.614- When assertions are necessary, add a comment justifying them.615- Use `satisfies` for type validation without assertion:616 ```typescript617 const palette = {618 red: [255, 0, 0],619 green: '#00ff00',620 } satisfies Record<string, string | number[]>;621 ```622623---624625## 16. React & JSX (when applicable)626627```tsx628// ✅ Good — functional component with explicit props type629interface UserCardProps {630 readonly user: User;631 readonly onSelect?: (userId: string) => void;632}633634export function UserCard({ user, onSelect }: UserCardProps): React.ReactElement {635 const handleClick = useCallback(() => {636 onSelect?.(user.id);637 }, [onSelect, user.id]);638639 return (640 <div className="user-card" onClick={handleClick} role="button" tabIndex={0}>641 <h3>{user.name}</h3>642 <p>{user.email}</p>643 </div>644 );645}646```647648### Rules649650- Use **function declarations** or **named function expressions** for components (not anonymous).651- Define props as an `interface` (e.g., `UserCardProps`), not inline.652- Mark all props as `readonly`.653- **Do NOT** use `React.FC` — it is discouraged since React 18.654- Use `React.ReactElement` or `React.ReactNode` as return type annotation.655- Colocate styles, tests, and types with the component when practical.656- Prefer **controlled components** over uncontrolled.657- Memoize expensive computations with `useMemo`, stable callbacks with `useCallback`.658- Extract custom hooks when logic is reused across components.659- Component file structure:660 1. Imports661 2. Types / Interfaces662 3. Constants663 4. Component function664 5. Helper functions (private to the module)665666---667668## 17. Testing Conventions669670```typescript671// ✅ Good — descriptive test structure672describe('UserService', () => {673 describe('findById', () => {674 it('should return the user when the id exists', async () => {675 const user = await service.findById('user-1');676 expect(user).toEqual(expect.objectContaining({ id: 'user-1' }));677 });678679 it('should return undefined when the id does not exist', async () => {680 const user = await service.findById('non-existent');681 expect(user).toBeUndefined();682 });683 });684});685```686687### Rules688689- Test files are colocated or in a `__tests__` directory.690- Name test files `*.test.ts` or `*.spec.ts`.691- Follow the **Arrange → Act → Assert** pattern.692- One assertion concept per test (multiple `expect` calls are okay if they test one logical693 assertion).694- Use **descriptive test names** that read like a sentence.695- Mock external dependencies; do NOT mock the module under test.696- Prefer **dependency injection** to make code testable.697- Aim for high test coverage on business logic; don't chase 100% on boilerplate.698- Use `jest.fn()` or equivalent for spies/mocks; type them properly:699 ```typescript700 const mockFetch = jest.fn<Promise<User>, [string]>();701 ```702703---704705## 18. Tooling & Configuration706707### Recommended `tsconfig.json` (Baseline)708709```jsonc710{711 "compilerOptions": {712 "target": "ES2022",713 "module": "NodeNext",714 "moduleResolution": "NodeNext",715 "lib": ["ES2022"],716 "strict": true,717 "esModuleInterop": true,718 "skipLibCheck": true,719 "forceConsistentCasingInFileNames": true,720 "resolveJsonModule": true,721 "isolatedModules": true,722 "declaration": true,723 "declarationMap": true,724 "sourceMap": true,725 "noUnusedLocals": true,726 "noUnusedParameters": true,727 "noFallthroughCasesInSwitch": true,728 "noUncheckedIndexedAccess": true,729 "exactOptionalPropertyTypes": true730 }731}732```733734### Recommended ESLint Rules735736| Rule | Setting |737| ---------------------------------------- | --------- |738| `@typescript-eslint/no-explicit-any` | `error` |739| `@typescript-eslint/explicit-function-return-type` | `warn` (for exported functions) |740| `@typescript-eslint/no-unused-vars` | `error` |741| `@typescript-eslint/consistent-type-imports` | `error` |742| `@typescript-eslint/no-non-null-assertion` | `warn` |743| `@typescript-eslint/prefer-nullish-coalescing` | `error` |744| `@typescript-eslint/prefer-optional-chain` | `error` |745| `@typescript-eslint/strict-boolean-expressions` | `warn` |746| `@typescript-eslint/naming-convention` | `error` (configured per construct) |747748---749750## Usage751752### Natural Language Activation753754Simply mention **TypeScript** in your conversation — the skill activates automatically.755756**Example prompts:**757758| Prompt | Skill Response |759|---|---|760| "Write a TypeScript function to merge two objects deeply" | Generates a fully typed, standards-compliant `deepMerge<T, U>()` function following all rules above. |761| "Review my TypeScript code for style issues" | Analyses the provided code against this guide and suggests improvements. |762| "Convert this JavaScript to TypeScript" | Converts code, adds strict types, interfaces, and follows all naming / formatting conventions. |763| "What's the TypeScript best practice for error handling?" | Explains the Result pattern, custom error classes, and typed catch blocks per §10. |764| "Create a TypeScript React component for a data table" | Generates a well-typed functional component following §16 React rules with proper props interface. |765| "Set up a new TypeScript project" | Provides `tsconfig.json`, ESLint config, Prettier config, and project structure following §18. |766767### Inline Rule References768769You can ask about any specific section:770771- *"Explain TypeScript naming conventions"* → References §2772- *"How should I handle null in TypeScript?"* → References §14773- *"Show me TypeScript generic best practices"* → References §9