Skip to content

Literal Inference & NoInfer

The Course
•
20 min study

Intermediate introduced as const. A const type parameter applies a similar literal-preservation preference to an inferred call argument. In function define<const T>(value:T):T, an inline literal can retain its precise readonly shape. This is a checking decision, not Object.freeze.

Preserve a literal before controlling inference

Compare ordinary generic inference with const inference on an inline record. The ordinary record's mode widens to string; the const version retains the literal "safe" and a readonly property. An annotation of exactly "safe" lets you check the difference without printing a type.

See literal inferenceTypeScript
function remember<T>(value: T): T {
  return value;
}

function keep<const T>(value: T): T {
  return value;
}

const ordinary = remember({ mode: "safe" });
const precise = keep({ mode: "safe" });

ordinary.mode = "fast";

const exact: "safe" = precise.mode;

console.log(ordinary.mode, exact);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
fast safe

Choose which argument supplies evidence

Inference can also gather evidence from more than one argument. If the first argument supplies allowed modes and the second is a default, you may want only the allowed list to determine T. Built-in NoInfer<T> prevents that second position from contributing candidates, while still checking its compatibility with T.

Without NoInfer, an incompatible fallback can help widen T. For example, a helper with fallback: T can infer "safe" | "fast" | "typo" from pick(["safe", "fast"], "typo"). That compiles because inference considered both arguments. Our desired rule is stricter: the first argument defines the choices, and the second must fit them. The error lab tests that rule.

Read the pickMode signature in order: T must be a string, allowed provides readonly choices, and fallback must be one of the inferred choices. The runtime includes check remains useful for untyped callers or invalid assertions. NoInfer does not validate an arbitrary value from JSON.

These features are available in the pinned TypeScript 5.9.3 compiler. Use them when they improve a real caller contract; an ordinary annotation is often enough. Passing an already widened string[] cannot recover its original literal members by adding const to a later function.

Predict, check, and run

Write the output before running. Use Check types first, then Check & run. Types disappear at runtime: explain both what the compiler checks and what the code actually does. Each editor is an independent ES module; await asynchronous work explicitly.

Predict, then runTypeScript
function pickMode<const T extends string>(
  allowed: readonly T[],
  fallback: NoInfer<T>
): T {
  if (!allowed.includes(fallback)) {
    throw new Error("Invalid fallback");
  }

  return fallback;
}

console.log(pickMode(["safe", "fast"], "safe"));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
safe

Read the compiler error

Predict the rejected relationship before checking. Read the real diagnostic and its source location; fix the contract or the value instead of hiding it with an assertion.

Find and fix the type errorTypeScript
function choose<const T extends string>(
  choices: readonly T[],
  fallback: NoInfer<T>
): T {
  return fallback;
}

console.log(choose(["small", "large"], "medium"));

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The key line is TS2345: Argument of type '"medium"' is not assignable to parameter of type '"small" | "large"'. The parameter type lists exactly the literals inferred from the first argument; NoInfer kept the fallback from adding to that list.

The first argument determines small|large. NoInfer stops medium from expanding that set through the fallback argument.

Trace the contract before building

Literal precision is useful when a particular string determines a particular result. Follow the value from its declaration to the generic call and identify where it might widen into string. Preserve the specific information only where the API needs it; ordinary mutable data may appropriately have a broader type.

Const-oriented inference does not freeze a runtime object or validate text arriving from outside the program. Try an authored literal and then a variable whose value can change. Explain why the second call may produce a less precise result. The goal is accurate evidence for each call, without promising that a dynamic value is a particular literal forever.

Build it yourself

Exercise

Literal Inference & NoInfer: practice

Write createPicker<const T extends string>(options) where options is an object with choices (a readonly list) and initial. It returns a function that takes any text and returns that text if it is one of the choices, otherwise initial. The return type must be the literal union of the choices. With choices light and dark and initial light, picking dark prints dark and picking blue prints light. initial: "blue" must be a compiler error.

Your workspaceTypeScript
// Write createPicker, then try the two picks and the invalid initial.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The choices alone should decide T, even though both properties sit in the same options object. Without help, the checker also uses initial as a source for T, so "blue" would quietly join the union.

Hint 2: a first step

Type the options as { choices: readonly T[]; initial: NoInfer<T> }. The returned function receives a plain string, so it needs a runtime membership test that narrows the text to T before returning it.

Show one solution
One possible solutionTypeScript
function createPicker<const T extends string>(options: {
  choices: readonly T[];
  initial: NoInfer<T>;
}): (text: string) => T {
  const isChoice = (text: string): text is T =>
    options.choices.some(choice => choice === text);

  return text => (isChoice(text) ? text : options.initial);
}

const pickTheme = createPicker({ choices: ["light", "dark"], initial: "light" });

console.log(pickTheme("dark"));
console.log(pickTheme("blue"));

Enable JavaScript to edit and type-check this example.

Text
dark
light

NoInfer works on a property inside an object parameter just as on a separate parameter: T is inferred from choices only, so initial: "blue" gives TS2322 "Type '"blue"' is not assignable to type '"light" | "dark"'". Remove NoInfer and the same call compiles, T widens to "light" | "dark" | "blue", and pickTheme("blue") returns "blue": the bug moves from the compiler to runtime. The text is T predicate is the runtime evidence; the const modifier keeps the literals but checks nothing about the text a user types.

Change it and test it

Assign the list to a string[] variable before calling choose and observe how the contract widens. Compare this with an as const list and explain why inference cannot recover discarded information.

Was this article helpful?

Your response is saved on this device.