Explicit Type Arguments
You'll learn how to manually specify generic type parameters when TypeScript's inference isn't enough or when you want to be explicit for clarity.
The Default Behavior
So far, you've learned that TypeScript can infer generic type arguments automatically at call sites. When you call a generic function, TypeScript looks at the arguments you pass and figures out what the type parameters should be:
function identity<T>(value: T): T {
return value;
}
const result = identity("hello"); // T inferred as string
This works great most of the time. But sometimes inference fails, produces the wrong type, or you simply want to be explicit.
Specifying Type Arguments Explicitly
You can override or supplement inference by providing explicit type arguments using angle brackets right after the function name:
function identity<T>(value: T): T {
return value;
}
// Explicitly tell TypeScript that T should be string
const result = identity<string>("hello");
// Force a specific type even when it could be inferred more narrowly
const num = identity<number>(42);
The syntax is: functionName<TypeArg1, TypeArg2>(arguments).
When You Need Explicit Type Arguments
1. Inference produces any or is ambiguous:
Sometimes TypeScript can't figure out what you want without more context.
2. You want a wider type than what gets inferred: Inference might give you a literal type when you want the broader primitive.
3. Multiple type parameters with partial inference: If a function has several type parameters and only some are inferrable, you may need to specify the rest.
4. Clarity and documentation: Being explicit can make your intent clearer to other developers.
Think of It Like This
Type inference is like auto-pilot — works great most of the time. Explicit type arguments are like taking manual control when you need precision or when auto-pilot doesn't have enough information.
Key Takeaway: Use angle brackets after the function name to explicitly specify generic type arguments when inference isn't sufficient or when you want to enforce a specific type at the call site.