typescript
Provide best-practice coding conventions and generate standards-compliant TypeScript code.
What this skill does
# 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](#1-general-principles)
2. [Naming Conventions](#2-naming-conventions)
3. [Types & Interfaces](#3-types--interfaces)
4. [Enums](#4-enums)
5. [Variables & Constants](#5-variables--constants)
6. [Functions](#6-functions)
7. [Classes](#7-classes)
8. [Modules & Imports](#8-modules--imports)
9. [Generics](#9-generics)
10. [Error Handling](#10-error-handling)
11. [Async / Await & Promises](#11-async--await--promises)
12. [Comments & Documentation](#12-comments--documentation)
13. [Formatting & Style](#13-formatting--style)
14. [Null & Undefined Handling](#14-null--undefined-handling)
15. [Type Assertions & Guards](#15-type-assertions--guards)
16. [React & JSX (when applicable)](#16-react--jsx-when-applicable)
17. [Testing Conventions](#17-testing-conventions)
18. [Tooling & Configuration](#18-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
```typescript
// ✅ 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
- Always annotate function return types explicitly for public APIs.
- Let TypeScript infer types for local variables when the type is obvious.
- Prefer `type` over `interface` for function signatures:
```typescript
type Comparator<T> = (a: T, b: T) => number;
```
- Avoid empty interfaces. If extending, include at least a comment explaining intent.
- Use `Record<K, V>` instead of `{ [key: string]: V }`.
- Use utility types (`Partial<T>`, `Pick<T, K>`, `Omit<T, K>`, `Required<T>`) to derive types
rather than duplicating.
---
## 4. Enums
### Prefer String Enums
```typescript
// ✅ 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
```typescript
// ✅ 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
```typescript
// ✅ 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:
```typescript
// ✅ Good
const { name, age } = user;
// ❌ Bad
const name = user.name;
const age = user.age;
```
- Use `as const` for immutable literal objects / arrays:
```typescript
const ROUTES = {
home: '/',
about: '/about',
contact: '/contact',
} as const;
```
---
## 6. Functions
### Function Declarations
```typescript
// ✅ 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:
```typescript
// ✅ Good
interface CreateUserOptions {
name: string;
email: string;
role?: Role;
department?: string;
}
function createUser(options: CreateUserOptions): User { ... }
// ❌ Bad — too many positional parameters
funRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.