NoInfer<T> for Disabling Inference
What you'll learn: How to prevent TypeScript from inferring a type parameter in specific positions to gain more control over generic function behavior.
The Core Idea
By default, TypeScript is eager to infer type parameters from all arguments you pass to a generic function. Sometimes this causes problems: one argument might incorrectly influence the inferred type, leading to unexpected behavior or loss of type safety.
NoInfer<T> is a utility type that blocks inference for a specific position while still allowing the type to flow through once determined elsewhere. Think of it like putting a one-way mirror on a window: you can see out (the type flows in), but no one can see in (no inference happens from this position).
When It Matters
Imagine a function that creates an object with default values, then allows overrides:
function createConfig<T>(defaults: T, overrides: T): T {
return { ...defaults, ...overrides };
}
const config = createConfig(
{ timeout: 1000, retries: 3 },
{ timeout: 2000 } // Error: Property 'retries' is missing
);
Here, TypeScript infers T from both arguments, creating a conflict. You want defaults to define the shape, but overrides to be a partial subset without influencing inference.
Using NoInfer<T>:
function createConfig<T>(defaults: T, overrides: Partial<NoInfer<T>>): T {
return { ...defaults, ...overrides };
}
const config = createConfig(
{ timeout: 1000, retries: 3 },
{ timeout: 2000 } // Now valid!
);
Now overrides uses T (so it's type-safe), but doesn't contribute to inferring what T is. Only defaults controls inference.
Key Takeaway: NoInfer<T> prevents a type parameter from being inferred in specific positions, giving you precise control over which arguments drive generic type inference.