How to Stop TypeScript from Silently Accepting Invalid Values: The Built-in NoInfer<T> TypeBrief · digest for November 20
Brief≈ 2 min

How to Stop TypeScript from Silently Accepting Invalid Values: The Built-in NoInfer<T> Type

You pass a list of payment methods ["card", "cash"] into a generic function and accidentally type "crypto" as the default second argument. You expect a red squiggle, yet TypeScript compiles the code without a complaint.

Type inference is to blame: the compiler guesses T from your arguments. When the same T appears in both parameters, TypeScript collects candidates from everywhere and widens the type to "card" | "cash" | "crypto". Since TypeScript 5.4, the built-in NoInfer<T> utility fixes this by blocking T from being inferred from a chosen parameter while keeping normal type checking and IDE autocomplete.

// Without NoInfer<T>: TS widens T to "card" | "cash" | "crypto"
declare function chooseDefaultBad<T extends string>(
  options: T[], fallback: T,
): T;

// With NoInfer<T>: only options acts as the source of truth
declare function chooseDefault<T extends string>(
  options: T[], fallback: NoInfer<T>,
): T;

chooseDefaultBad(["card", "cash"], "crypto"); // No error
chooseDefault(["card", "cash"], "card");      // OK
chooseDefault(["card", "cash"], "crypto");    // Type error

Before this, you had to add a clumsy second generic like <T extends string, D extends T>. Now a single wrapper does the job with zero runtime code—just remember that NoInfer<T> only protects you at compile time and doesn't replace validating external inputs.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2