Overriding Inferred Types
What you'll learn: When and how to explicitly provide type arguments to generic functions or types, overriding TypeScript's automatic inference.
TypeScript's type inference for generics is usually excellent—it looks at your arguments and figures out the right type parameters automatically. But sometimes the inferred type isn't what you need, or you want to be more specific than what inference would produce.
When Inference Needs a Nudge
Consider a generic function that creates an array. If you call it with no arguments, TypeScript might infer never[] (an array of nothing). Or if you pass mixed values, it might infer a union type when you actually want a more specific type.
You can override inferred types by explicitly providing type arguments in angle brackets:
function createArray<T>(): T[] {
return [];
}
// Inferred as never[]
const arr1 = createArray();
// Explicitly override to string[]
const arr2 = createArray<string>();
Common Override Scenarios
Widening or narrowing the type:
function identity<T>(value: T): T {
return value;
}
const num = identity(42); // Inferred as 42 (literal)
const wider = identity<number>(42); // Override to number
Fixing ambiguous inference:
function merge<T, U>(a: T, b: U) {
return { ...a, ...b };
}
// Explicitly state both types when inference isn't clear
const result = merge<{ x: number }, { y: string }>({ x: 1 }, { y: "hi" });
Key Takeaway: While TypeScript's generic inference is powerful, you can always explicitly pass type arguments with angle brackets when you need more control or specificity than inference provides.