TypeScript
by @wscats
Provide best-practice coding conventions and generate standards-compliant TypeScript code.
clawhub install typescript-skillsπ About This Skill
name: typescript slug: typescript license: MIT description: > Provide best-practice coding conventions and generate standards-compliant TypeScript code.
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
1. General Principles 2. Naming Conventions 3. Types & Interfaces 4. Enums 5. Variables & Constants 6. Functions 7. Classes 8. Modules & Imports 9. Generics 10. Error Handling 11. Async / Await & Promises 12. Comments & Documentation 13. Formatting & Style 14. Null & Undefined Handling 15. Type Assertions & Guards 16. React & JSX (when applicable) 17. Testing Conventions 18. Tooling & Configuration
1. General Principles
"strict": true in tsconfig.json. This turns on noImplicitAny,strictNullChecks, strictFunctionTypes, and more.
any: Treat every use of any as tech debt. Prefer unknown when the type isconst over let; prefer readonly properties andReadonlyArray / Readonly utility types.
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
I (e.g., ~~IUser~~ β User).Type or Interface.i, j) or generic type parameters (T, K, V).
IO, ID); 3+ characters use PascalCaseHttp, 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 = Success | 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
type over interface for function signatures: type Comparator = (a: T, b: T) => number;
Record instead of { [key: string]: V }.Partial, Pick, Omit, Required) to derive types4. 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
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
const unless the variable needs reassignment; then use let.var. // β
Good
const { name, age } = user; // β Bad
const name = user.name;
const age = user.age;
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
// β
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 { ... }
arguments; use rest parameters (...args) instead.Function type. Use specific function signatures. // β
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 {
return this.repository.get(id);
}
}
Rules
readonly for properties that should not change after construction.public, protected, private) on every member._. TypeScript's private keyword is sufficient.# (ES private fields) when true runtime privacy is required. class Logger {
constructor(private readonly prefix: string) {}
}
class UserRepositoryImpl implements UserRepository { ... }
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
import type / export type for type-only imports to help bundlers tree-shake: import type { User } from './user';
node:fs, node:path)
2. External packages (react, lodash)
3. Internal aliases (@/utils, @/components)
4. Relative parent (../)
5. Relative sibling (./)
import * as) unless re-exporting a module namespace.index.ts) thin β do not add logic.9. Generics
// β
Good β descriptive when intent is ambiguous
function merge(target: TTarget, source: TSource): TTarget & TSource {
return { ...target, ...source };
}// β
Good β single-letter when intent is obvious
function identity(value: T): T {
return value;
}
// β
Good β constrained generics
function getProperty(obj: T, key: K): T[K] {
return obj[key];
}
Rules
T, U, K, V) for simple generics.T (TKey, TValue, TResult) when there are).Array, Promise, Map) over their shorthand where10. 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(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
catch blocks).Error for domain-specific errors.catch variable as unknown (default in TS 4.4+) and narrow before use. type Result = { ok: true; value: T } | { ok: false; error: E };
finally blocks or use disposable patterns.11. Async / Await & Promises
// β
Good β async/await
async function fetchUser(id: string): Promise {
const response = await httpClient.get(/users/${id});
return response.data;
}// β
Good β parallel execution
async function fetchDashboard(userId: string): Promise {
const [user, posts, notifications] = await Promise.all([
fetchUser(userId),
fetchPosts(userId),
fetchNotifications(userId),
]);
return { user, posts, notifications };
}
Rules
async/await over .then() chains for readability.Promise.Promise.all() for independent concurrent operations.Promise.allSettled() when failures should not abort sibling operations.new Promise() when an async function suffices (avoid the explicit-constructionasync void functions β they cannot be await-ed and swallow errors.void.
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
/** */) for all public APIs, exported functions, classes, interfaces, and types.@param, @returns, @throws, and @example tags where applicable.// TODO: with a ticket number for planned improvements.// FIXME: for known issues that need resolution.// HACK: for workarounds that should be revisited.13. Formatting & Style
General
') for strings; backticks (` `) for template literals.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
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"arrowParens": "always"
}
and 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 {
kind: 'success';
data: T;
}
interface Failure {
kind: 'failure';
error: Error;
}
type Result = Success | Failure;
function handleResult(result: Result): 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;
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 (
{user.name}
{user.email}
);
}
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:
1. Imports
2. Types / Interfaces
3. Constants
4. Component function
5. 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
Test files are colocated or in a __tests__ directory.
Name test files *.test.ts or *.spec.ts.
Follow the Arrange β Act β Assert pattern.
One assertion concept per test (multiple expect calls are okay if they test one logical
assertion).
Use descriptive test names that read like a sentence.
Mock external dependencies; do NOT mock the module under test.
Prefer dependency injection to make code testable.
Aim for high test coverage on business logic; don't chase 100% on boilerplate.
Use jest.fn() or equivalent for spies/mocks; type them properly:
const mockFetch = jest.fn, [string]>();
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 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:
π‘ Examples
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 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:
π Constraints
type over interface for function signatures: type Comparator = (a: T, b: T) => number;
Record instead of { [key: string]: V }.Partial, Pick, Omit, Required) to derive types