Skip to content

prefer-option ​

A value that may be missing is written Option<T>, not T | undefined. An idiomatic rule: reported only with "safe-ts": { "idiomatic": true } in package.json.

Why: Option<T> is T | undefined, so the types are the same and so is the runtime cost: none. The point is one spelling. A codebase that writes absence both ways (a bulk null → undefined rewrite leaves T | undefined behind) reads as if the two meant different things, and Option is the name you can search for, the one no-nested-option and no-unknown-in-result look at. A failure is a Result<T, E>, not an Option: see no-swallowed-error. Guide: Absence.

✕ Rejectedprefer-option
ts
export type Discount = { readonly percent: number; readonly label: string };

export function discount(startsAt: number, t: number): Discount | undefined {
  if (t < startsAt) return undefined;
  return { percent: 10, label: "spring sale" };
}
✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";

export type Discount = { readonly percent: number; readonly label: string };

// The sale hasn't started at `t`: no discount. Absence, not a failure, and free on a hot path.
export function discount(startsAt: number, t: number): Option<Discount> {
  if (t < startsAt) return undefined;
  return { percent: 10, label: "spring sale" };
}

Return types, parameters, fields (holder?: Option<string> too), variables and type arguments (Map<string, Option<number>>) all count. Not reported:

  • T | null and T | null | undefined: no-null reports those, and its fix writes Option<T>;
  • unions with void, any, unknown or never in them, or an Option<...> member;
  • Option<T | undefined>: that's no-nested-option;
  • the declaration of a type named Option, and .d.ts files.

Quick fix: Write as Option<...>, which adds import type { Option } from @evobug_com/safe-ts-std/result when the file doesn't have it (nothing with the prelude). No fix is offered in a file that has its own Option (a select box's option type, say). For a whole codebase, the undefined-to-option codemod applies every fix at once.

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