# Idiomatic TypeScript: 10 patterns with before-and-after code

> Ten idiomatic TypeScript patterns, each compiled under strict mode: literal unions over enums, satisfies over as, unknown at boundaries, exhaustive switches.

- Canonical HTML: [https://unrust.dev/blog/idiomatic-typescript-patterns](https://unrust.dev/blog/idiomatic-typescript-patterns)
- Markdown representation: [https://unrust.dev/blog/idiomatic-typescript-patterns/index.md](https://unrust.dev/blog/idiomatic-typescript-patterns/index.md)

Published: 2026-11-11. By the Unrust team.

## What is idiomatic TypeScript?

Idiomatic TypeScript is code that lets the compiler prove as much as possible while staying plain JavaScript at runtime. In practice that means: let inference type local values, model alternatives as unions, check untrusted data instead of asserting it, and avoid syntax that emits runtime code. A reviewer should be able to see every assumption the types rely on.

Every example below was compiled with TypeScript 6.0.3 on November 11, 2026, with strict, noUncheckedIndexedAccess, erasableSyntaxOnly and verbatimModuleSyntax switched on. The error codes and messages quoted are the ones tsc printed. TypeScript 7.0, the native Go port released in 2026, is described by Microsoft as a faithful port built to keep results consistent with 6.0, so the same checks apply.

The table below is the short version. Each row is one section below, with the code to avoid, the code to prefer and the compiler output that separates them.

```text
#   Instead of                              Prefer                                   What it buys
--  --------------------------------------  ---------------------------------------  ------------------------------------------
1   Annotating every local variable         Inference inside, annotations at edges   Less noise; signatures stay the contract
2   enum                                    Literal union from an as const array     No runtime emit; works with type stripping
3   as Type, or a wide annotation           satisfies Type                           Checked shape; exact keys and literals kept
4   JSON.parse(text) as T                   unknown, then narrow or parse            Bad payloads fail at the boundary
5   One type with optional fields           Discriminated union                      Impossible states cannot be built
6   switch that silently falls through      never-based exhaustiveness check         A new variant breaks the build, not prod
7   Mutable array parameters                readonly T[] plus toSorted or slice      Callers' arrays are never reordered
8   filter(Boolean) or filter(...) as T[]   Inferred type predicates (TS 5.5+)       Narrowing without a cast
9   Copy-pasted object types                typeof, keyof, Pick, Omit, T["key"]      One source of truth
10  value! non-null assertions              Narrow, or throw with a message          Failures name the missing value
```

## 1. Let inference type locals; annotate the edges

Annotate function parameters and the return types of exported functions, and let TypeScript infer everything inside the body. The TypeScript handbook notes that inference covers most variable declarations. Annotations on locals repeat what the compiler already knows, and they can widen a type: const mode: string = "dark" throws away the literal "dark".

Explicit return types on exported functions are worth keeping. They stop an accidental change in the body from silently changing the public type, and the isolatedDeclarations option added in TypeScript 5.5 requires them. Inside a function, an annotation earns its place when inference has nothing to work from, such as a variable declared before it is assigned: let selected: User | undefined;

```javascript
type User = { id: string; name: string; email: string; active: boolean };

// Before: every local repeats a type the compiler already knows
function activeNames(users: User[]) {
  const active: User[] = users.filter((u: User): boolean => u.active);
  const names: string[] = active.map((u: User): string => u.name);
  return names;
}

// After: the signature is the contract, the body is inferred
export function activeNames(users: readonly User[]): string[] {
  return users.filter((u) => u.active).map((u) => u.name);
}
```

## 2. Use a literal union instead of an enum

Prefer a union of string literals, derived from an as const array, over an enum. Enums are one of the few TypeScript features that emit runtime code, so Node.js type stripping cannot run them and erasableSyntaxOnly flags them. A string enum also rejects the plain string it stands for, so callers must import the enum to pass "draft".

The as const array gives you what the enum gave you at runtime, a list you can iterate and validate against, while the type stays erasable. The cast inside isStatus widens the tuple to readonly string[] so includes accepts any string. A widening cast cannot hide a missing field, unlike the narrowing casts in pattern 3. The TypeScript handbook itself says an object with as const may be all you need instead of an enum.

Node.js runs .ts files by stripping types: on by default since v22.18.0 and v23.6.0, and marked stable in v24.12.0 and v25.2.0. Stripping only deletes type syntax, so enum declarations, namespaces with runtime code and parameter properties raise an error. erasableSyntaxOnly, added in TypeScript 5.8, reports those constructs at compile time instead of at startup.

```javascript
// Before
enum Status {
  Draft = "draft",
  Published = "published",
}
function label(status: Status): string {
  return status.toUpperCase();
}
label("draft");
// error TS2345: Argument of type '"draft"' is not assignable to parameter of type 'Status'.
// With erasableSyntaxOnly, the enum declaration itself also reports:
// error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.

// After
export const STATUSES = ["draft", "published", "archived"] as const;
export type Status = (typeof STATUSES)[number]; // "draft" | "published" | "archived"

export function isStatus(value: string): value is Status {
  return (STATUSES as readonly string[]).includes(value);
}

function label(status: Status): string {
  return status.toUpperCase();
}
label("draft"); // OK
isStatus("deleted"); // false
```

## 3. Use satisfies instead of as for object literals

Use satisfies when an object literal should be checked against a type without losing its own, more precise type. An as assertion lets a missing field through, and a wide annotation such as Record<string, Route> forgets which keys exist. satisfies, added in TypeScript 4.9, catches both mistakes and keeps the literal values.

The satisfies version keeps literal types as well: routes.admin.auth is typed true, not boolean, so code that branches on it can narrow. With noUncheckedIndexedAccess on, the annotated version does report TS18048, 'routes.admn' is possibly 'undefined', but only satisfies tells you the key is a typo and autocompletes the real ones.

Keep as for the cases where you know more than the compiler and can point at the evidence, such as a value a parser has just checked. as const is not a cast in that sense: it asks for the narrowest literal type and cannot make a wrong value compile.

```javascript
type Route = { path: string; auth: boolean };

// Before: as accepts a missing field
const home = { path: "/" } as Route; // compiles; home.auth is undefined at runtime

// Before: the annotation forgets which keys exist
const routes: Record<string, Route> = {
  home: { path: "/", auth: false },
  admin: { path: "/admin", auth: true },
};
routes.admn.path; // compiles under plain strict; throws a TypeError at runtime

// After
const home = { path: "/" } satisfies Route;
// error TS1360: Type '{ path: string; }' does not satisfy the expected type 'Route'.
//   Property 'auth' is missing in type '{ path: string; }' but required in type 'Route'.

const routes = {
  home: { path: "/", auth: false },
  admin: { path: "/admin", auth: true },
} satisfies Record<string, Route>;
routes.admn;
// error TS2551: Property 'admn' does not exist on type
//   '{ home: { path: string; auth: false; }; admin: { path: string; auth: true; }; }'.
//   Did you mean 'admin'?
```

## 4. Type untrusted input as unknown, then narrow it

Treat anything that crosses a runtime boundary, such as JSON.parse output, a request body or a queue message, as unknown and narrow it before use. JSON.parse returns any, and as Invoice compiles whether or not the payload matches. A narrowing function turns a bad payload into an error at the boundary instead of a wrong total three calls later.

Since TypeScript 4.9, an in check on an object narrows it to a type that has that property, so the guard needs no assertion. Returning a fresh object also drops unexpected extra fields. Called with { id: "x", amountCents: "50" }, parseInvoice throws Invalid invoice payload. For larger shapes, a schema validation library does the same job with less code; the idiom is the unknown-then-validate boundary, not the hand-written guard.

Truthiness checks and custom type predicates at these boundaries have their own traps, such as if (value) skipping a valid 0. The Unrust guide on TypeScript type narrowing and runtime boundaries covers those in a review table.

```javascript
type Invoice = { id: string; amountCents: number };

// Before: compiles for any payload, including {"amountCents":"50"}
const invoice = JSON.parse(text) as Invoice;

// After
function parseInvoice(value: unknown): Invoice {
  if (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "string" &&
    "amountCents" in value &&
    typeof value.amountCents === "number"
  ) {
    return { id: value.id, amountCents: value.amountCents };
  }
  throw new Error("Invalid invoice payload");
}

const invoice = parseInvoice(JSON.parse(text));
```

## 5. Model states as discriminated unions

When a value can be in one of several states, give each state its own member of a union with a shared literal tag, instead of one type with optional fields. The tag tells the compiler which fields exist in each branch, so a success state without data, or an error state without a message, cannot be built.

In the before version the compiler is right to complain: nothing stops code from building { status: "success" } with no data. A common way to silence the error is state.data!, which moves the bug to runtime. In the after version, checking state.status === "success" narrows state to the member that has data, and no assertion is needed.

```javascript
// Before: 3 statuses x 2 optional fields = 12 shapes, most of them impossible
type RequestState = {
  status: "loading" | "success" | "error";
  data?: User[];
  error?: string;
};
// Reading state.data.length after checking status === "success":
// error TS18048: 'state.data' is possibly 'undefined'.

// After: one member per state, tagged by status
type RequestState =
  | { status: "loading" }
  | { status: "success"; data: User[] }
  | { status: "error"; error: string };
```

## 6. Make every switch exhaustive with never

End a switch over a union with a default branch that passes the value to a function whose parameter is never. When every case is handled, the value has narrowed to never and the call compiles. When the union gains a member, every switch that forgot it fails to build, instead of the new state falling through at runtime.

A switch that returns from every case already gets part of this check for free: with a declared return type, a missing case reports TS2366, Function lacks ending return statement and return type does not include 'undefined'. assertNever extends the check to switches that do not return a value, and it names the missing member in the error.

Keep the throw. Types do not exist at runtime, so a payload with an unexpected status still reaches default, and failing with the value in the message beats returning undefined. The TypeScript handbook describes the same never-based exhaustiveness check in its chapter on narrowing.

```javascript
function assertNever(value: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}

function render(state: RequestState): string {
  switch (state.status) {
    case "loading":
      return "Loading";
    case "success":
      return `${state.data.length} users`;
    case "error":
      return `Failed: ${state.error}`;
    default:
      return assertNever(state);
  }
}

// Later, someone adds | { status: "idle" } to RequestState:
// error TS2345: Argument of type '{ status: "idle"; }' is not assignable to parameter of type 'never'.
```

## 7. Accept readonly arrays and copy before sorting

Type array parameters you do not intend to change as readonly T[], and use non-mutating methods such as toSorted, slice or a spread copy. Array.prototype.sort reorders in place, so a function that sorts its argument silently reorders the caller's array. With readonly, the compiler rejects the mutating call, and callers can still pass ordinary arrays.

toSorted is part of ES2023: it needs lib es2023 or later and a runtime such as Node.js 20 or newer. On older targets, [...scores].sort(...) does the same job. readonly is shallow: readonly User[] blocks push, sort and splice on the array, but still lets you assign to a property of an element. Use Readonly<User> or readonly properties when the elements must be protected too.

```javascript
// Before: reorders the caller's array as a side effect
function topThree(scores: number[]): number[] {
  return scores.sort((a, b) => b - a).slice(0, 3);
}
// With a readonly parameter, the same body is rejected:
// error TS2339: Property 'sort' does not exist on type 'readonly number[]'.

// After
function topThree(scores: readonly number[]): number[] {
  return scores.toSorted((a, b) => b - a).slice(0, 3);
}

const scores = [70, 95, 88, 61];
console.log(topThree(scores), scores); // [ 95, 88, 70 ] [ 70, 95, 88, 61 ]
```

## 8. Let filter infer the type predicate

Since TypeScript 5.5, an arrow function such as id => id !== undefined is inferred as a type predicate, so filter narrows the element type without a cast. filter(Boolean) does not narrow: the result is still (string | undefined)[], and it also drops empty strings and zeros. Write the comparison you mean and let inference do the rest.

Inference only produces a predicate when true and false map cleanly onto the type. That is why id => !!id is not inferred as one: an empty string is a string that returns false. The as string[] cast compiles, but it also removes "" without saying so. When you need a reusable guard, write it out, function isDefined<T>(x: T | undefined): x is T, and keep its body as strict as its claim.

```javascript
const maybeIds: (string | undefined)[] = ["a1", undefined, "b2"];

// Before
const viaBoolean = maybeIds.filter(Boolean); // (string | undefined)[]
viaBoolean.map((id) => id.toUpperCase());
// error TS18048: 'id' is possibly 'undefined'.
const viaCast = maybeIds.filter((id) => !!id) as string[]; // compiles; also drops ""

// After (TypeScript 5.5+)
const ids = maybeIds.filter((id) => id !== undefined); // string[]
console.log(ids.map((id) => id.toUpperCase())); // [ 'A1', 'B2' ]
```

## 9. Derive types instead of copying them

When one type is a view of another, derive it with typeof, keyof, indexed access or utility types such as Pick, Omit and Partial instead of retyping the fields. A copied type silently drifts the first time the original changes. A derived type cannot drift. Keep one source of truth, usually the domain type or a constant value.

Derivation can go too far. A conditional type that computes a form's props from a database schema through five layers is derived, and still hard to review. If a reviewer has to hover over a type to learn what it contains, name the intermediate steps or write the shape out once.

```javascript
type User = { id: string; name: string; email: string; active: boolean };

// Before: a second copy that will drift
type UserSummary = { id: string; name: string };

// After
type UserSummary = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id">;
type UserEmail = User["email"]; // string

const defaultConfig = { retries: 3, timeoutMs: 5000, region: "eu-west-1" };
type Config = typeof defaultConfig; // { retries: number; timeoutMs: number; region: string }
type ConfigKey = keyof Config; // "retries" | "timeoutMs" | "region"
```

## 10. Narrow or throw instead of the non-null assertion

Replace value! with an explicit check that throws a descriptive error. The ! operator removes null and undefined from the type without any runtime check, so a missing value surfaces later as Cannot read properties of undefined, far from its cause. The check costs three lines and its error message names what was missing.

The same applies to index reads under noUncheckedIndexedAccess, where list[0] has type T | undefined. If an earlier line guarantees the element exists, a ! with a comment pointing at that line can be acceptable. If you cannot point at the line, the assertion is a guess.

```javascript
const usersById = new Map<string, User>();

// Before: compiles; crashes later if the id is unknown
const user = usersById.get(id)!;

// After
function requireUser(id: string): User {
  const user = usersById.get(id);
  if (user === undefined) {
    throw new Error(`Unknown user ${id}`);
  }
  return user;
}
```

## Quick check: which two lines would you flag?

Given a string called input, this snippet compiles under strict with noUncheckedIndexedAccess. Name the two lines that rely on an unchecked assumption, say what each one assumes, and predict what the compiler does when someone adds { kind: "triangle"; base: number; height: number } to Shape.

```javascript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

const shapes = JSON.parse(input) as Shape[];
const largest = shapes.toSorted((a, b) => area(b) - area(a))[0]!;

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
  }
}
```

### Answer and explanation

Flag the JSON.parse line and the ! line. The first asserts that untrusted input is an array of valid shapes, which is pattern 4: nothing checks it, so a payload with a misspelled kind reaches area and returns undefined. The second assumes the array is not empty, which is pattern 10: for an empty payload, largest is undefined despite its type, and the crash happens wherever largest is first used.

Adding the triangle member breaks the build at area with error TS2366: Function lacks ending return statement and return type does not include 'undefined'. Because every case returns and the return type is declared, the switch is already exhaustive-checked. A switch that only performed side effects would need the assertNever default from pattern 6 to get the same protection.

## A tsconfig baseline for idiomatic TypeScript

Idioms are easier to keep when the compiler enforces them. strict has been on by default since TypeScript 6.0. Add noUncheckedIndexedAccess so index reads include undefined, and, if you run .ts files with Node.js type stripping, add erasableSyntaxOnly and verbatimModuleSyntax so the compiler rejects syntax the runtime cannot strip.

strict is listed explicitly so the file means the same thing under TypeScript 5.x, where the default was false. verbatimModuleSyntax requires import type for imports used only as types; Node.js needs that keyword to know an import can be deleted. noUncheckedIndexedAccess is not part of strict and is the flag most likely to produce a burst of errors in an existing codebase, so enable it per package if a single switch is too much.

```json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true
  }
}
```

## When the non-idiomatic version is the right call

Idioms are defaults, not rules. Keep existing enums when a codebase uses them consistently and never runs on a type-stripping runtime. Keep an as after a validator has already checked the value. Keep a wider type when the precise one would take longer to read than the bug it prevents. Match the surrounding code before importing a pattern from elsewhere.

Generated API clients, framework conventions and older compiler targets also change the answer. The Unrust guide on idiomatic code makes the same point across JavaScript, Python and TypeScript: a suggested change should explain what became clearer to the reader and confirm that behavior stayed the same.

## Idiomatic TypeScript code review checklist

Use these questions on a TypeScript diff. Each maps to a pattern above and to text you can search for in the changed lines, so the review takes minutes rather than a full reread. A hit is not automatically a defect; it is a line where the author should be able to point at the evidence behind the type.

```text
Question                                                       Pattern   Search the diff for
-------------------------------------------------------------  --------  -------------------------------
Does an as narrow a value nobody has checked?                  3, 4      " as " (skip "as const")
Does a ! lack a line that proves the value exists?             10        "!." and "!;"
Is untrusted input typed any or asserted to a domain type?     4         "JSON.parse", ": any", "as any"
Does a new enum ship to a type-stripping runtime?              2         "enum "
Could a state type hold an impossible combination?             5         "?:" beside a status field
Will a new union member fail the build at every switch?        6         "switch (", "default:"
Does a function reorder or mutate an array it was given?       7         ".sort(", ".reverse(", ".splice("
Is a type copied field by field from another type?             9         repeated property lists
```

## Practise reading TypeScript for idiom

Reading for idiom is a skill you can practise: look at a snippet, decide whether it compiles and what it does, then check. Unrust's free diagnostic samples Idiom / Quality as one of six skills, alongside recall, tracing, comprehension, debugging and AI-slop detection, and you can take it in JavaScript, TypeScript or Python.

The diagnostic takes about 14 minutes with AI and hints off, and a free account then gives you a daily practice queue. For an untimed TypeScript exercise, the explicit-false challenge in Unrust's public code review lab shows why options.showHints || true erases an explicit false while ?? keeps it.

## Idiomatic TypeScript: FAQ

What does idiomatic TypeScript mean? Code that uses the language the way experienced TypeScript developers expect: inferred locals, explicit signatures at module edges, unions instead of enums and optional-field bags, and runtime checks instead of assertions. It compiles under strict settings without casts doing work that a check should do.

Are enums bad in TypeScript? Not bad, but no longer the default choice. They emit runtime code, so Node.js type stripping cannot run them and erasableSyntaxOnly reports them, and string enums reject the plain strings they represent. A literal union derived from an as const array covers most uses and still gives you a runtime list.

When should I use satisfies instead of a type annotation? Use satisfies on object literals when you want the value checked but want to keep its exact keys and literal types, as with route tables and configuration maps. Use an annotation when you want the wider type, for example a variable that will be reassigned to other values of that type.

Is any ever idiomatic? Rarely in application code. unknown accepts the same values but forces a check before use, so it is the idiomatic type for untrusted input. any can be a reasonable stopgap during a JavaScript-to-TypeScript migration or in a test double, ideally tracked by a lint rule so it does not spread.

Does TypeScript 7 change what idiomatic TypeScript looks like? No. TypeScript 7.0 is a native port of the compiler, built to keep results consistent with 6.0. The changes that matter for idioms came earlier: satisfies in 4.9, inferred type predicates in 5.5, erasableSyntaxOnly in 5.8 and strict on by default in 6.0.

## References and next steps

[TypeScript Handbook: Everyday Types (type annotations on variables)](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html)
[TypeScript Handbook: Enums, objects vs enums](https://www.typescriptlang.org/docs/handbook/enums.html)
[TypeScript 4.9 release notes: the satisfies operator and in narrowing](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html)
[TypeScript Handbook: Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html)
[TypeScript 5.5 release notes: inferred type predicates](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-5.html)
[TypeScript 5.8 release notes: the erasableSyntaxOnly option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-8.html)
[TypeScript 6.0 release notes: simple default changes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-6-0.html)
[TSConfig reference: noUncheckedIndexedAccess](https://www.typescriptlang.org/tsconfig/#noUncheckedIndexedAccess)
[Node.js documentation: Modules, TypeScript](https://nodejs.org/api/typescript.html)
[Announcing TypeScript 7.0 (Microsoft TypeScript blog)](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/)
[MDN: Array.prototype.toSorted()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted)

[Practise writing idiomatic TypeScript with clear types](https://unrust.dev/languages/typescript/idiomatic-code/index.md)

## Read TypeScript for idiom against the clock

Take Unrust's free diagnostic in TypeScript with AI and hints closed: about 14 minutes. Idiom / Quality is one of six skills it samples, alongside recall, tracing, comprehension, debugging and AI-slop detection.

[Take the free diagnostic](https://unrust.dev/diagnostic/index.md)
