Bird
Raised Fist0
Typescriptprogramming~10 mins

How TypeScript infers generic types - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - How TypeScript infers generic types
Call generic function with argument
↓
TypeScript checks argument type
↓
Infer generic type from argument
↓
Use inferred type inside function
↓
Return or process value with inferred type
TypeScript looks at the argument you pass to a generic function and figures out the generic type automatically, so you don't have to specify it.
Execution Sample
Typescript
function identity<T>(arg: T): T {
  return arg;
}

const result = identity(42);
This code defines a generic function identity and calls it with a number; TypeScript infers T as number.
Execution Table
StepActionInput/ArgumentInferred Type TReturn Value
1Call identity with 4242number
2Infer generic type T from argument42number
3Execute function bodyarg = 42number42
4Return valuenumber42
5Assign to resultnumber42
💡 Function completes after returning the argument with inferred type number.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
argundefined424242
Tunknownnumbernumbernumber
resultundefinedundefinedundefined42
Key Moments - 3 Insights
Why don't we need to specify the type T when calling identity(42)?
Because TypeScript looks at the argument 42 and automatically infers that T is number, as shown in execution_table step 2.
What happens if we call identity with a string instead?
TypeScript will infer T as string, similar to how it inferred number for 42, following the same steps in the execution_table.
Can TypeScript infer generic types from multiple arguments?
Yes, TypeScript tries to infer the generic type from all arguments, but if it can't, you may need to specify the type explicitly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the inferred type T at step 2 when calling identity(42)?
Astring
Bnumber
Cany
Dunknown
💡 Hint
Check the 'Inferred Type T' column at step 2 in the execution_table.
At which step does the function return the value 42?
AStep 4
BStep 3
CStep 1
DStep 5
💡 Hint
Look at the 'Return Value' column in the execution_table.
If we call identity('hello'), how would the inferred type T change in the variable_tracker?
AT would be number
BT would be any
CT would be string
DT would be undefined
💡 Hint
Refer to how T changes from unknown to number in variable_tracker; it changes to the argument's type.
Concept Snapshot
Generic functions let you write reusable code.
TypeScript infers the generic type from the argument you pass.
You don't need to specify the type explicitly.
The inferred type is used inside the function.
Example: identity(42) infers T as number.
Full Transcript
This visual execution shows how TypeScript infers generic types when calling a generic function. When identity is called with 42, TypeScript looks at the argument and infers that the generic type T is number. The function then uses this inferred type to process and return the value. Variables like arg and result hold the value 42, and T is tracked as number. This automatic inference means you don't have to write the type explicitly, making code simpler and safer.

Practice

(1/5)
1. What does TypeScript do when you call a generic function without specifying the type explicitly?
easy
A. It ignores the generic and treats the function as non-generic.
B. It throws a compilation error asking for the type.
C. It guesses the generic type based on the arguments you pass.
D. It always uses the type any by default.

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    It guesses the generic type based on the arguments you pass. -> Option C
  4. Quick Check:

    Type inference = guessing type from arguments [OK]
Hint: Remember: TypeScript guesses generic types from arguments [OK]
Common Mistakes:
  • Thinking TypeScript requires explicit generic types always
  • Assuming it defaults to any type
  • Believing generic types are ignored if not specified
2. Which of the following is the correct syntax to define a generic function in TypeScript that returns the same type it receives?
easy
A. function identity<T>(arg: T): T { return arg; }
B. function identity(arg: T): T { return arg; }
C. function identity<T>(arg): T { return arg; }
D. function identity<T>(arg: T): any { return arg; }

Solution

  1. Step 1: Check generic function syntax

    The generic type parameter T must be declared before the function parameters inside angle brackets <T>.
  2. Step 2: Verify parameter and return types

    The parameter arg should be typed as T, and the return type should also be T to return the same type.
  3. Final Answer:

    function identity<T>(arg: T): T { return arg; } -> Option A
  4. Quick Check:

    Generic syntax = <T> before parameters [OK]
Hint: Generic type <T> goes before parameters in function definition [OK]
Common Mistakes:
  • Omitting <T> before parameters
  • Not typing the argument as T
  • Returning any instead of T
3. What will be the output of this TypeScript code?
function wrapInArray<T>(value: T) {
  return [value];
}

const result = wrapInArray(42);
console.log(typeof result[0]);
medium
A. "number"
B. "string"
C. "object"
D. "undefined"

Solution

  1. Step 1: Identify the generic type inferred

    The function wrapInArray is called with 42, a number, so TypeScript infers T as number.
  2. Step 2: Check the returned array and logged type

    The function returns an array containing the number 42. Accessing result[0] gives 42, so typeof result[0] is "number".
  3. Final Answer:

    "number" -> Option A
  4. Quick Check:

    typeof 42 = "number" [OK]
Hint: Generic type matches argument type, so typeof matches argument [OK]
Common Mistakes:
  • Assuming the type is string by default
  • Confusing array type with element type
  • Expecting 'object' because of array
4. Consider this code snippet:
function firstElement<T>(arr: T[]): T {
  return arr[0];
}

const value = firstElement([true, false, true]);
console.log(value.toUpperCase());

What is the problem here?
medium
A. The array passed is empty, so arr[0] is undefined.
B. TypeScript cannot infer the generic type T.
C. The function firstElement returns an array instead of an element.
D. Calling toUpperCase() on a boolean causes a compile-time error.

Solution

  1. Step 1: Analyze the inferred generic type

    The array [true, false, true] is of type boolean[], so T is inferred as boolean.
  2. Step 2: Check the method call on the returned value

    The function returns a boolean, but toUpperCase() is a string method. Calling it on a boolean causes a compile-time error.
  3. Final Answer:

    Calling toUpperCase() on a boolean causes a compile-time error. -> Option D
  4. Quick Check:

    Boolean has no toUpperCase() method [OK]
Hint: Check if method matches the inferred type before calling [OK]
Common Mistakes:
  • Thinking TypeScript inference failed
  • Assuming function returns array instead of element
  • Ignoring compile-time errors from wrong method calls
5. You want to write a generic function 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};
}
hard
A. TypeScript infers both T and U as object losing specific properties.
B. TypeScript infers T as {name: string} and U as {age: number}, returning their intersection type.
C. TypeScript cannot infer generic types for multiple parameters automatically.
D. TypeScript infers T and U as any by default.

Solution

  1. 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}.
  2. Step 2: Understand TypeScript's inference for multiple generics

    TypeScript infers T as the type of the first argument and U as the type of the second argument automatically.
  3. Step 3: Check the return type

    The return type is the intersection T & U, meaning the combined object has both name and age properties.
  4. Final Answer:

    TypeScript infers T as {name: string} and U as {age: number}, returning their intersection type. -> Option B
  5. Quick Check:

    Multiple generics inferred from each argument [OK]
Hint: Each generic inferred from corresponding argument type [OK]
Common Mistakes:
  • Assuming generic types default to object or any
  • Thinking TypeScript can't infer multiple generics
  • Confusing intersection type with union type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard