Skip to content

Typing without casts ​

When an as cast or Reflect escape hatch feels unavoidable, there is almost always a cleaner, type-checked pattern. Every recipe on this page came out of migrating a large codebase and replaced a cast flagged by no-unchecked-cast.

In short

  • Missing package fields: extend third-party types cleanly with declare module augmentation instead of casting.
  • Unavoidable runtime bridges: isolate them behind trust<T> or typed mapped-object builders rather than scattering as across call sites.
  • Class internals & overrides: prefer protected members and subclasses over prototype patching or casts.

Packages ​

A field the package's type lacks: module augmentation ​

A server keeps the logged-in user on each ws socket. WebSocket has no such field, so the first attempt casts:

✕ Rejectedno-unchecked-cast
ts
import type { WebSocket } from "ws";

export function who(socket: WebSocket): string {
  return (socket as WebSocket & { userId?: string }).userId ?? "guest";
}

Declare the field on the package's own type instead. An interface written inside declare module "<package>" merges with the package's declaration of the same name, a class included, so every WebSocket in the program has the field and nothing is cast:

✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
import type { Option } from "@evobug_com/safe-ts-std/result";
import type { WebSocket } from "ws";

declare module "ws" {
  interface WebSocket {
    /** Set once the client has logged in. */
    userId?: Option<string>;
  }
}

export function logIn(socket: Mut<WebSocket>, userId: string): void {
  socket.userId = userId;
}

export function who(socket: WebSocket): string {
  return socket.userId ?? "guest";
}

Make the field optional: the package creates the objects and doesn't know about it, so a field added as always there is a cast with no as (no-unchecked-declare); safe-ts check counts the declare module either way, among the ambient declarations:

ts
import type { WebSocket } from "ws";

declare module "ws" {
  interface WebSocket {
    sessionId: string;
  }
}

export function session(socket: WebSocket): string {
  return socket.sessionId;
}

For a generic interface, repeat its type parameters exactly as the package declares them (interface Container<T extends Item = Item> { ... }), or the declarations don't merge. Some packages ask for this: vue-router's RouteMeta is the documented place for typed route meta fields.

A precise result the body can't type: trust ​

statusCodes(["pending", "paid", "shipped"]) numbers a list of order statuses. Built with Object.fromEntries, the result is typed { [k: string]: number }, and something has to say which keys it has. An overload over a loose implementation looks like it says that without a cast, but TypeScript checks the body only against the implementation's signature and trusts the overload, so it is a cast nobody can find (no-overload):

✕ Rejectedno-overload
ts
export function statusCodes<const T extends readonly string[]>(names: T): { readonly [K in T[number]]: number };
export function statusCodes(names: readonly string[]): { readonly [name: string]: number } {
  return Object.freeze(Object.fromEntries(names.map((name, i) => [name, i])));
}
ts
export function statusCodes<const T extends readonly string[]>(names: T): { readonly [K in T[number]]: number };
export function statusCodes(names: readonly string[]): { readonly [name: string]: number } {
  { const __la1 = names; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let name = __le1; let i = __li1; __lr1[__li1] = ([name, i]); }} return Object.freeze(Object.fromEntries(__lr1)); }
}

Say the claim where it is made, with trust<T>(value) (std result): it is searchable, safe-ts check counts it among the escape hatches, and the body next to it is short enough to see that it is true. A type that walks the tuple still turns a misuse into a compile error, here a status listed twice:

✓ Accepted0 diagnostics
ts
import { trust } from "@evobug_com/safe-ts-std/result";

/** The first name that appears twice in `T`, or `never` when they are all different. */
type Duplicate<T extends readonly string[], Seen extends string = never> = T extends readonly [
  infer Head extends string,
  ...infer Rest extends readonly string[],
]
  ? Head extends Seen
    ? Head
    : Duplicate<Rest, Seen | Head>
  : never;

/** `T` when its names are all different, otherwise a type that names the duplicate. */
type Unique<T extends readonly string[]> = [Duplicate<T>] extends [never] ? T : readonly [`"${Duplicate<T>}" appears twice`];

/** One number per order status, in list order. */
export function statusCodes<const T extends readonly string[]>(names: Unique<T>): { readonly [K in T[number]]: number } {
  const list: readonly string[] = names;
  // `Object.fromEntries` can't say which keys it makes: each name of the list, its index.
  return trust<{ readonly [K in T[number]]: number }>(Object.freeze(Object.fromEntries(list.map((name, i) => [name, i]))));
}

export const Status = statusCodes(["pending", "paid", "shipped"]);
export const paid: number = Status.paid;

// @ts-expect-error: "paid" appears twice
statusCodes(["pending", "paid", "paid"]);
ts
import { trust } from "@evobug_com/safe-ts-std/result";

/** The first name that appears twice in `T`, or `never` when they are all different. */
type Duplicate<T extends readonly string[], Seen extends string = never> = T extends readonly [
  infer Head extends string,
  ...infer Rest extends readonly string[],
]
  ? Head extends Seen
    ? Head
    : Duplicate<Rest, Seen | Head>
  : never;

/** `T` when its names are all different, otherwise a type that names the duplicate. */
type Unique<T extends readonly string[]> = [Duplicate<T>] extends [never] ? T : readonly [`"${Duplicate<T>}" appears twice`];

/** One number per order status, in list order. */
export function statusCodes<const T extends readonly string[]>(names: Unique<T>): { readonly [K in T[number]]: number } {
  const list: readonly string[] = names;
  // `Object.fromEntries` can't say which keys it makes: each name of the list, its index.
  { const __la1 = list; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let name = __le1; let i = __li1; __lr1[__li1] = ([name, i]); }} return trust<{ readonly [K in T[number]]: number }>(Object.freeze(Object.fromEntries(__lr1))); }
}

export const Status = statusCodes(["pending", "paid", "shipped"]);
export const paid: number = Status.paid;

// @ts-expect-error: "paid" appears twice
statusCodes(["pending", "paid", "paid"]);

Duplicate is tail-recursive (the recursive call is the whole result of its branch), which TypeScript evaluates as a loop, so a list of hundreds of names stays within its limits.

A check that builds a mapped type: return what it built ​

A generic check can't claim its result with value is PriceTable<K> (no-type-predicate: TypeScript doesn't check a predicate's body). It can build the table from what it checked and return it: recordOf(keys, f) (std dict) makes a Record<K, V> with exactly the keys asked for, so the caller gets those keys without a claim:

✓ Accepted0 diagnostics
ts
import { recordOf } from "@evobug_com/safe-ts-std/dict";
import type { Option } from "@evobug_com/safe-ts-std/result";

/** A table with one number per key in `K`. */
export type PriceTable<K extends string> = { readonly [P in K]: number };

export function priceTable<const K extends string>(value: unknown, keys: readonly K[]): Option<PriceTable<K>> {
  if (typeof value !== "object" || value === null) return undefined;
  const prices = new Map<K, number>();
  for (const key of keys) {
    const price: unknown = Reflect.get(value, key);
    if (typeof price !== "number") return undefined;
    prices.set(key, price);
  }
  return recordOf(keys, (key) => prices.get(key) ?? 0);
}

export function shippingCost(config: unknown, size: "small" | "large"): Option<number> {
  const prices = priceTable(config, ["small", "large"]);
  return prices === undefined ? undefined : prices[size]; // prices: PriceTable<"small" | "large">
}

For data with a declared type, validate<T> writes the whole check for you.

Calling a library's protected member ​

TypeScript hides protected members from code outside the class on purpose, so outside code can't call one through the class's type, and nothing in SAFE-TS changes that. What works without a cast:

  • You create the object: subclass it and call the member from inside, where TypeScript allows it and checks the call.
  • The library created it: look the method up on an object view of the value. in and typeof narrow it to a function, and calling it as a method keeps this.
✓ Accepted0 diagnostics
ts
// Stands for a class from a charting library.
declare class Chart {
  constructor(canvas: HTMLCanvasElement);
  protected redraw(): void;
}

// You create the object: subclass it.
export class SalesChart extends Chart {
  refresh(): void {
    this.redraw();
  }
}

// The library created it: look the method up.
export function refresh(chart: Chart): void {
  const view: object = chart;
  if ("redraw" in view && typeof view.redraw === "function") view.redraw();
}

The second form gives up the type of the call (arguments and result are unchecked), so use it for methods without arguments, or prefer the subclass. It reads better than Reflect.get(chart, "redraw") plus Reflect.apply, which needs the same test.

Objects ​

Calling a method on an object of the right shape: .call ​

An Invoice method can total a draft from a form that has the same fields but isn't an Invoice. Invoice.prototype.total.call(draft) is typed: with strict, TypeScript checks the arguments and gives the method's result type. Reflect.apply(Invoice.prototype.total, draft, []) returns any instead, and typescript-eslint's unbound-method reports the method it takes off its object (SAFE-TS's unbound-method doesn't: Reflect.apply hands the object over with it). Declare a this parameter and the object passed to .call is checked too; without one, any object is accepted:

✓ Accepted0 diagnostics
ts
type Line = { readonly price: number; readonly quantity: number };

export class Invoice {
  constructor(
    readonly lines: readonly Line[],
    readonly discount: number,
  ) {}

  // `this:` names what the method needs, so `.call` checks the object it gets.
  total(this: { readonly lines: readonly Line[]; readonly discount: number }): number {
    const sum = this.lines.reduce((s, line) => s + line.price * line.quantity, 0);
    return sum - this.discount;
  }
}

// A draft from the form has the fields but isn't an `Invoice`.
export function draftTotal(draft: { lines: Line[]; discount: number }): number {
  return Invoice.prototype.total.call(draft);
}

"Is it an object?": typeof, not instanceof Object ​

x instanceof Object asks whether Object.prototype is on the prototype chain, and a dictionary made with Object.create(null) has no prototype at all. Libraries make them for lookup tables, and so does Node: querystring.parse returns one. Test the type instead:

✓ Accepted0 diagnostics
ts
import { parse } from "node:querystring";

// No `: value is object`: TypeScript infers it from the body, and checks it.
export function isObject(value: unknown) {
  return typeof value === "object" && value !== null;
}

const query = parse("page=2&sort=price");
export const viaInstanceof = query instanceof Object; // false
export const viaTypeof = isObject(query); // true

Extending a library object: a subclass, not a patched method ​

An uploader that shows a preview has to release the preview's URL when it is destroyed. Replacing uploader.destroy on an object you were given changes it for its owner (no-param-mutation), and the next reader has to find the patch to know what destroy() does:

✕ Rejectedno-param-mutation
ts
// Stands for a class from an upload library.
declare class Uploader {
  constructor(file: File);
  destroy(): void;
}

export function releaseOnDestroy(uploader: Uploader, preview: string): void {
  const destroy = uploader.destroy.bind(uploader);
  uploader.destroy = () => {
    URL.revokeObjectURL(preview);
    destroy();
  };
}

A subclass says it in the type, and override makes TypeScript check that the method exists:

✓ Accepted0 diagnostics
ts
// Stands for a class from an upload library.
declare class Uploader {
  constructor(file: File);
  start(): void;
  destroy(): void;
}

// The preview URL lives as long as the uploader, and is released in the same place.
export class PreviewUploader extends Uploader {
  readonly preview: string;

  constructor(file: File) {
    super(file);
    this.preview = URL.createObjectURL(file);
  }

  override destroy(): void {
    URL.revokeObjectURL(this.preview);
    super.destroy();
  }
}

Building a key name: a template literal as const ​

`${variant}Button` is a string, so it can't index a table with known keys without a cast. as const (which isn't a cast: it only keeps the literal type) types it as the template literal type, here "primaryButton" | "dangerButton":

✓ Accepted0 diagnostics
ts
type Variant = "primary" | "danger";

const styles = {
  primaryButton: "bg-blue text-white",
  dangerButton: "bg-red text-white",
} as const;

export function buttonClass(variant: Variant): string {
  const key = `${variant}Button` as const;
  return styles[key];
}

A key that is only an identity: Object.freeze({}) ​

Sometimes a value only has to be different from every other value: the owner of a lock, a "no one" marker in a Map<object, ...>. Object.freeze({}) is that, and freezing it keeps anyone from hanging data on it later:

✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";

/** Takes a document's edit lock for the server itself rather than for a browser tab. */
export const SERVER = Object.freeze({});

export function createLock() {
  let holder: Option<object> = undefined;
  return {
    acquire(owner: object): boolean {
      if (holder !== undefined && holder !== owner) return false;
      holder = owner;
      return true;
    },
    release(owner: object): void {
      if (holder === owner) holder = undefined;
    },
  };
}

export function migrate(lock: ReturnType<typeof createLock>): boolean {
  return lock.acquire(SERVER);
}

Rules in this guide: no-unchecked-cast, no-param-mutation

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra