What if your code could guess the right types for you, saving time and mistakes?
How TypeScript infers generic types - Why You Should Know This
Imagine you have a function that works with different types of data, like numbers or strings, and you have to write separate versions for each type manually.
For example, one function for numbers, another for strings, and so on.
This manual approach is slow and repetitive.
Every time you want to support a new type, you write more code, increasing chances of mistakes and making your program harder to maintain.
TypeScript's generic type inference automatically figures out the types you use when calling a function.
This means you write one flexible function, and TypeScript fills in the correct types for you behind the scenes.
function identityNumber(value: number): number { return value; }
function identityString(value: string): string { return value; }function identity<T>(value: T): T { return value; }
const num = identity(123);
const str = identity('hello');This lets you write reusable, type-safe code that adapts automatically to different data types without extra work.
Think of a function that returns the first item of any list, whether it's a list of names, numbers, or dates, without rewriting it for each type.
Manual type-specific functions are repetitive and error-prone.
TypeScript infers generic types to simplify and secure your code.
You write one function that works for many types automatically.
Practice
Solution
Step 1: Understand generic function calls
When you call a generic function without specifying the type, TypeScript tries to figure out the type from the arguments you provide.Step 2: Check TypeScript behavior
TypeScript uses the argument types to infer the generic type automatically, so you don't have to write it explicitly.Final Answer:
It guesses the generic type based on the arguments you pass. -> Option CQuick Check:
Type inference = guessing type from arguments [OK]
- Thinking TypeScript requires explicit generic types always
- Assuming it defaults to any type
- Believing generic types are ignored if not specified
Solution
Step 1: Check generic function syntax
The generic type parameterTmust be declared before the function parameters inside angle brackets <T>.Step 2: Verify parameter and return types
The parameterargshould be typed asT, and the return type should also beTto return the same type.Final Answer:
function identity<T>(arg: T): T { return arg; } -> Option AQuick Check:
Generic syntax = <T> before parameters [OK]
- Omitting <T> before parameters
- Not typing the argument as T
- Returning any instead of T
function wrapInArray<T>(value: T) {
return [value];
}
const result = wrapInArray(42);
console.log(typeof result[0]);Solution
Step 1: Identify the generic type inferred
The functionwrapInArrayis called with42, a number, so TypeScript infersTasnumber.Step 2: Check the returned array and logged type
The function returns an array containing the number42. Accessingresult[0]gives42, sotypeof result[0]is "number".Final Answer:
"number" -> Option AQuick Check:
typeof 42 = "number" [OK]
- Assuming the type is string by default
- Confusing array type with element type
- Expecting 'object' because of array
function firstElement<T>(arr: T[]): T {
return arr[0];
}
const value = firstElement([true, false, true]);
console.log(value.toUpperCase());What is the problem here?
Solution
Step 1: Analyze the inferred generic type
The array[true, false, true]is of typeboolean[], soTis inferred asboolean.Step 2: Check the method call on the returned value
The function returns aboolean, buttoUpperCase()is a string method. Calling it on a boolean causes a compile-time error.Final Answer:
CallingtoUpperCase()on a boolean causes a compile-time error. -> Option DQuick Check:
Boolean has no toUpperCase() method [OK]
- Thinking TypeScript inference failed
- Assuming function returns array instead of element
- Ignoring compile-time errors from wrong method calls
mergeObjects that takes two objects and returns a new object combining both. How does TypeScript infer the generic types when you call mergeObjects({name: "Alice"}, {age: 30})?function mergeObjects(obj1: T, obj2: U): T & U {
return {...obj1, ...obj2};
}Solution
Step 1: Identify argument types passed to the function
The first argument is{name: "Alice"}which has type{name: string}. The second is{age: 30}with type{age: number}.Step 2: Understand TypeScript's inference for multiple generics
TypeScript infersTas the type of the first argument andUas the type of the second argument automatically.Step 3: Check the return type
The return type is the intersectionT & U, meaning the combined object has bothnameandageproperties.Final Answer:
TypeScript infersTas{name: string}andUas{age: number}, returning their intersection type. -> Option BQuick Check:
Multiple generics inferred from each argument [OK]
- Assuming generic types default to object or any
- Thinking TypeScript can't infer multiple generics
- Confusing intersection type with union type
Ready to prove it?
Pass the test and this pattern moves unknown
