Menu

Defaults, const Type Parameters, and NoInfer

Lesson 4: Defaults, const Type Parameters, and NoInfer

How can you control inference?

Feature Syntax Effect
Default type parameter <T = string> Used when T is not given or inferred
const type parameter <const T> Infers literal and read-only types, as if as const were written
NoInfer<T> (value: NoInfer<T>) Stops this position from influencing what T becomes

Example

// Default type parameter
type ApiError<TCode = string> = { code: TCode; message: string };
const e1: ApiError = { code: 'OUT_OF_STOCK', message: 'Item unavailable' };
const e2: ApiError<404 | 500> = { code: 404, message: 'Not found' };

// const type parameter
function defineSlots<const T extends readonly string[]>(slots: T): T {
  return slots;
}
const slots = defineSlots(['morning', 'afternoon', 'evening']);
// type: readonly ['morning', 'afternoon', 'evening'] (not string[])

// NoInfer
function createSelect<T extends string>(options: T[], defaultValue: NoInfer<T>) {
  return { options, value: defaultValue };
}
createSelect(['UPI', 'Card', 'COD'], 'UPI');    // OK
createSelect(['UPI', 'Card', 'COD'], 'Crypto');
// Error: '"Crypto"' is not assignable to '"UPI" | "Card" | "COD"'.

How it works

  • Defaults make generic types easier to use when one choice is common.
  • const type parameters save callers from writing as const, which is useful for configuration helpers and route definitions.
  • Without NoInfer, TypeScript would infer T from both arguments and accept 'Crypto' by widening T. NoInfer tells it to take T from options only.

Common mistakes

Mistake Effect Fix
Defaults on required type parameters before optional ones Error: required parameters must come first Put defaulted parameters last
Expecting const T to make arrays mutable Inferred as readonly Constrain with readonly string[]
Fighting inference with explicit arguments everywhere Verbose calls Use NoInfer on the positions that should not drive inference

Key takeaways

  • Default type parameters simplify common cases.
  • const type parameters and NoInfer help you get exactly the inference you intend.

Try it: Write defineRoutes with a const type parameter so that defineRoutes(['/cart', '/orders']) infers a tuple of literal paths.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details