| name | coding-typescript |
| description | TypeScript, JavaScript, React, and Node.js coding standards — naming conventions, type safety, error handling, immutability, React patterns, performance, and code quality. Always activate when writing, reviewing, or refactoring TypeScript or JavaScript code; setting up linting or type-checking; enforcing naming or structural conventions; or when the user asks how to structure a component, handle an error, type a value, or write a hook. Also activate proactively when spotting `any`, unsafe mutations, swallowed errors, or missing cleanup in user code. |
TypeScript & React Coding Standards
Consistent, type-safe, maintainable patterns for TypeScript, React, and Node.js.
Workflow
When this skill activates:
- Identify the task — new code, code review, refactor, or standards setup.
- Apply the relevant section — navigate directly; don't repeat unrelated rules.
- Flag violations proactively if spotted in user code —
any, unsafe mutations, swallowed errors, missing key props, and unguarded await response.json() are the most common.
- For extended patterns (Result types, barrel exports, advanced generics), see
references/advanced.md.
Core Principles
- Readability first — code is read far more than written; optimise for the reader
- KISS — simplest solution that works; no premature optimisation
- DRY — extract common logic; avoid copy-paste programming
- YAGNI — don't build features before they're needed; add complexity only when required
- Errors are information — never swallow them; always preserve the original cause
Naming
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000
const q = 'election'
const flag = true
const x = 1000
async function fetchMarketData(marketId: string): Promise<Market> { }
function calculateSimilarity(a: number[], b: number[]): number { }
function isValidEmail(email: string): boolean { }
async function market(id: string) { }
function similarity(a, b) { }
File Naming
components/Button.tsx # PascalCase for components
hooks/useAuth.ts # camelCase with 'use' prefix
lib/formatDate.ts # camelCase for utilities
types/market.types.ts # .types suffix
Type Safety
Never Use any — Use unknown with Narrowing
function process(data: any) {
return data.name.toUpperCase()
}
function process(data: unknown): string {
if (typeof data !== 'object' || data === null || !('name' in data)) {
throw new TypeError('Invalid data shape')
}
const { name } = data as { name: unknown }
if (typeof name !== 'string') throw new TypeError('name must be a string')
return name.toUpperCase()
}
Define Interfaces — Never Infer from any
interface Market {
id: string
name: string
status: 'active' | 'resolved' | 'closed'
createdAt: Date
}
function getMarket(id: string): Promise<Market> { }
function getMarket(id: any): Promise<any> { }
satisfies — Validate Without Widening (TS 4.9+)
const config = {
env: 'production',
timeout: 5000,
} satisfies Record<string, string | number>
config.env
const config: Record<string, string | number> = { env: 'production', timeout: 5000 }
config.env
Immutability
Mutate only with intent and a comment explaining why. The default is immutable.
const updatedUser = { ...user, name: 'New Name' }
const updatedItems = [...items, newItem]
const withoutFirst = items.slice(1)
const sortedMarkets = [...markets].sort((a, b) => b.volume - a.volume)
user.name = 'New Name'
items.push(newItem)
markets.sort((a, b) => b.volume - a.volume)
When mutation is genuinely justified (tight loop, large array, proven bottleneck), add a comment:
items.push(newItem)
Error Handling
Preserve the Cause Chain
async function fetchData(url: string): Promise<unknown> {
let response: Response
try {
response = await fetch(url)
} catch (cause) {
throw new Error(`Network request failed: ${url}`, { cause })
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
try {
return await response.json()
} catch (cause) {
throw new Error('Response body is not valid JSON', { cause })
}
}
async function fetchData(url: string) {
try {
const response = await fetch(url)
return response.json()
} catch (error) {
throw new Error('Failed to fetch data')
}
}
Narrow Caught Errors — They Are unknown in Strict Mode
try {
await riskyOperation()
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
logger.error('Operation failed', { message, cause: error })
throw error
}
Async Patterns
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats(),
])
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()
const results = await Promise.allSettled([fetchUsers(), fetchMarkets()])
for (const result of results) {
if (result.status === 'rejected') logger.warn('Partial fetch failed', { reason: result.reason })
}
React Patterns
Component Structure
interface ButtonProps {
children: React.ReactNode
onClick: () => void
disabled?: boolean
variant?: 'primary' | 'secondary'
}
export function Button({
children,
onClick,
disabled = false,
variant = 'primary',
}: ButtonProps) {
return (
<button onClick={onClick} disabled={disabled} className={`btn btn-${variant}`}>
{children}
</button>
)
}
List Rendering — Always Use key
{markets.map((market) => (
<MarketCard key={market.id} market={market} />
))}
{markets.map((market, i) => (
<MarketCard key={i} market={market} />
))}
useEffect — Always Return Cleanup
useEffect(() => {
const controller = new AbortController()
async function loadData() {
try {
const data = await fetchMarket(id, { signal: controller.signal })
setMarket(data)
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') return
setError(error instanceof Error ? error.message : 'Unknown error')
}
}
loadData()
return () => controller.abort()
}, [id])
useEffect(() => {
fetchMarket(id).then(setMarket)
}, [id])
State — Use Functional Updates
setCount(prev => prev + 1)
setItems(prev => [...prev, newItem])
setCount(count + 1)
Memoization — Measure Before Adding
const sortedMarkets = useMemo(
() => [...markets].sort((a, b) => b.volume - a.volume),
[markets],
)
const handleSearch = useCallback((query: string) => {
setSearchQuery(query)
}, [])
const doubled = useMemo(() => count * 2, [count])
Custom Hooks
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay)
return () => clearTimeout(handler)
}, [value, delay])
return debouncedValue
}
Conditional Rendering
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}
Lazy Loading
const HeavyChart = lazy(() => import('./HeavyChart'))
export function Dashboard() {
return (
<Suspense fallback={<Spinner />}>
<HeavyChart />
</Suspense>
)
}
Input Validation (API Routes)
Always guard request.json() — malformed bodies throw before Zod validation:
import { z } from 'zod'
import { NextRequest, NextResponse } from 'next/server'
const CreateMarketSchema = z.object({
name: z.string().min(1).max(200),
description: z.string().min(1).max(2000),
endDate: z.string().datetime(),
categories: z.array(z.string()).min(1),
})
export async function POST(request: NextRequest) {
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json(
{ error: { code: 'invalid_json', message: 'Request body is not valid JSON' } },
{ status: 400 },
)
}
const result = CreateMarketSchema.safeParse(body)
if (!result.success) {
return NextResponse.json(
{ error: { code: 'validation_error', message: 'Validation failed', details: result.error.issues } },
{ status: 422 },
)
}
const market = await createMarket(result.data)
return NextResponse.json({ data: market }, { status: 201 })
}
Code Smells
Long Functions
function processMarketData() { }
function processMarketData() {
const validated = validateData(raw)
const transformed = transformData(validated)
return saveData(transformed)
}
Deep Nesting — Use Guard Clauses
if (user) {
if (user.isAdmin) {
if (market?.isActive) {
if (hasPermission) { }
}
}
}
if (!user) return
if (!user.isAdmin) return
if (!market?.isActive) return
if (!hasPermission) return
Magic Numbers
if (retryCount > 3) { }
setTimeout(callback, 500)
const MAX_RETRIES = 3
const DEBOUNCE_DELAY_MS = 500
if (retryCount > MAX_RETRIES) { }
setTimeout(callback, DEBOUNCE_DELAY_MS)
Comments
const delay = Math.min(1000 * Math.pow(2, retryCount), 30_000)
count++
JSDoc for Public Functions
export async function searchMarkets(query: string, limit = 10): Promise<Market[]> { }
Testing
test('calculates cosine similarity correctly for orthogonal vectors', () => {
const vector1 = [1, 0, 0]
const vector2 = [0, 1, 0]
const similarity = calculateCosineSimilarity(vector1, vector2)
expect(similarity).toBe(0)
})
test('returns empty array when no markets match query', () => { })
test('throws when OpenAI API key is missing', () => { })
test('falls back to substring search when cache is unavailable', () => { })
test('works', () => { })
test('test search', () => { })
Performance
const { data } = await supabase
.from('markets')
.select('id, name, status')
.limit(10)
const { data } = await supabase.from('markets').select('*')
Project Structure (Next.js App Router)
src/
├── app/
│ ├── api/ # API route handlers
│ ├── markets/ # Market pages
│ └── (auth)/ # Auth pages (route group — no URL segment)
├── components/
│ ├── ui/ # Generic, reusable UI primitives
│ ├── forms/ # Form components
│ └── layouts/ # Layout wrappers
├── hooks/ # Custom React hooks (use*.ts)
├── lib/
│ ├── api/ # API clients and fetchers
│ ├── utils/ # Pure utility functions
│ └── constants/ # App-wide constants
├── types/ # Shared TypeScript interfaces
└── styles/ # Global CSS
For barrel exports, Result types, and advanced generics, see references/advanced.md.