---
name: typescript-best-practices
description: Core TypeScript conventions for type safety, inference, and clean code. Use when writing TypeScript, reviewing TypeScript code, creating interfaces/types, or when the user asks about TypeScript patterns, conventions, or best practices.
title: typescript-best-practices
canonical_url: https://skilld.dev/gh/grahamcrackers/skills/typescript-best-practices
last_updated: 2026-10-07T02:20:44.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install grahamcrackers/skills/typescript-best-practices`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/typescript-best-practices`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/grahamcrackers/skills/typescript-best-practices) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/typescript-best-practices`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/typescript-best-practices --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/typescript-best-practices --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# TypeScript Best Practices

## Type Safety

- Enable `strict: true` in `tsconfig.json` — never disable strict checks in production code.
- Prefer `unknown` over `any`. If `any` is unavoidable, add a comment explaining why and narrow it immediately.
- Use `satisfies` to validate a value matches a type while preserving its narrowed literal type:

```typescript
const config = {
    endpoint: "/api/users",
    timeout: 3000,
} satisfies Config;
```

- Prefer type narrowing (type guards, `in` operator, `instanceof`) over type assertions (`as`).

## Type Inference

- Let TypeScript infer when the type is obvious — don't annotate what the compiler already knows:

```typescript
// Redundant
const name: string = "Graham";

// Let it infer
const name = "Graham";
```

- Always annotate function return types for exported/public functions — it catches accidental return type changes and improves IDE performance:

```typescript
export function getUser(id: string): User | undefined {
    return users.get(id);
}
```

- Annotate function parameters — they cannot be inferred from implementation.

## Types vs Interfaces

- Use `type` for unions, intersections, mapped types, and utility types.
- Use `interface` for object shapes that may be extended or implemented.
- Be consistent within a codebase — pick one default and stick with it.

## Enums and Constants

- Prefer `as const` objects over `enum`:

```typescript
const Status = {
    Active: "active",
    Inactive: "inactive",
} as const;

type Status = (typeof Status)[keyof typeof Status];
```

- This gives you type safety, tree-shaking, and no runtime enum overhead.

## Null Handling

- Prefer explicit `| undefined` in types over optional properties when the distinction matters.
- Use optional chaining (`?.`) and nullish coalescing (`??`) over manual null checks.
- Avoid non-null assertions (`!`) — narrow the type instead.

## Generics

- Name generic parameters descriptively when there are multiple: `TInput`, `TOutput` instead of `T`, `U`.
- Constrain generics with `extends` to communicate intent:

```typescript
function merge<T extends Record<string, unknown>>(a: T, b: Partial<T>): T {
    return { ...a, ...b };
}
```

- Avoid over-genericizing — if a function only ever handles one type, don't make it generic.

## Utility Types

- Use built-in utility types (`Partial`, `Required`, `Pick`, `Omit`, `Record`, `Readonly`) instead of reimplementing them.
- `Readonly<T>` for data that should not be mutated.
- `Pick` and `Omit` to derive subsets from existing types rather than duplicating fields.

## Error Handling

- Type errors explicitly — don't rely on `catch (e)` being `any`:

```typescript
try {
    await fetchData();
} catch (error) {
    if (error instanceof ApiError) {
        handleApiError(error);
    }
    throw error;
}
```

- Create typed error classes for domain-specific errors.

## Module Organization

- One type/interface per concern — avoid monolithic `types.ts` files.
- Co-locate types with the code that uses them.
- Export types from barrel files only when they form part of the public API.
- Use `import type` / `export type` for type-only imports to enable proper tree-shaking.

## Naming Conventions

- PascalCase for types, interfaces, enums, and classes.
- camelCase for variables, functions, and methods.
- UPPER_SNAKE_CASE for true constants (compile-time values).
- Don't prefix interfaces with `I` or types with `T` — it's not C#.
