Bird
Raised Fist0
Typescriptprogramming~10 mins

Generic function syntax in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Generic function syntax
Define generic function with <T>
↓
Call function with specific type
↓
Function uses type T inside
↓
Return value of type T
↓
End
This flow shows how a generic function is defined with a type placeholder T, then called with a specific type, uses that type inside, and returns a value of that type.
Execution Sample
Typescript
function identity<T>(arg: T): T {
  return arg;
}

const output = identity<string>("hello");
console.log(output);
This code defines a generic function identity that returns the argument it receives, then calls it with a string and prints the result.
Execution Table
StepActionType TArgument (arg)Return ValueOutput
1Define function identity with generic type TT (generic)N/AN/AN/A
2Call identity with T = string and arg = "hello"string"hello"N/AN/A
3Inside function, return argstring"hello""hello"N/A
4Assign return value to outputstringN/A"hello"N/A
5Print outputstringN/AN/A"hello"
💡 Function completes after returning the argument; output is printed.
Variable Tracker
VariableStartAfter CallAfter ReturnFinal
argundefined"hello""hello"undefined (out of scope)
outputundefinedundefined"hello""hello"
Key Moments - 3 Insights
Why do we write <T> after the function name?
The <T> declares a placeholder type that the function can use inside. It means the function works with any type, not just one fixed type. See execution_table step 1.
How does the function know what type T is?
When we call the function, we specify the type, like identity<string>. This tells the function what T means for this call. See execution_table step 2.
What type does the function return?
It returns the same type T that was passed in, so if T is string, it returns a string. See execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'arg' at step 3?
Aundefined
B"hello"
CT (generic)
Dnull
💡 Hint
Check the 'Argument (arg)' column at step 3 in the execution_table.
At which step is the output variable assigned a value?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'Action' column for when output gets a value in the execution_table.
If we call identity<number>(5) instead, what would be the type of output?
Aany
Bstring
Cnumber
Dboolean
💡 Hint
Refer to the explanation in key_moments about how T is set at call time.
Concept Snapshot
Generic function syntax:
function funcName<T>(arg: T): T {
  return arg;
}
- <T> declares a type placeholder.
- Caller specifies actual type.
- Function uses T inside and returns T.
- Enables reusable, type-safe functions.
Full Transcript
This visual execution shows how a generic function in TypeScript works. First, the function identity is defined with a generic type T. Then, it is called with T set to string and argument "hello". Inside the function, the argument is returned as the same type T. The returned value is assigned to output and printed. Variables arg and output change as the function runs. Key points include that <T> declares a placeholder type, the caller sets the actual type, and the function returns the same type. The quizzes test understanding of variable values at steps and how types are assigned.

Practice

(1/5)
1. What does the <T> represent in a TypeScript generic function?
easy
A. A placeholder for a type that will be specified later
B. A variable name for a function parameter
C. A special keyword to declare a constant
D. A syntax error in TypeScript

Solution

  1. Step 1: Understand generic syntax

    The <T> syntax is used to declare a generic type parameter in TypeScript functions.
  2. Step 2: Identify the role of T

    It acts as a placeholder for any type that will be provided when the function is called, making the function reusable for different types.
  3. Final Answer:

    A placeholder for a type that will be specified later -> Option A
  4. Quick Check:

    Generic <T> = Type placeholder [OK]
Hint: Remember <T> means 'type to be decided' [OK]
Common Mistakes:
  • Thinking T is a variable name
  • Confusing <T> with a function argument
  • Assuming <T> is a TypeScript keyword
2. Which of the following is the correct syntax to declare a generic function named identity that returns the same type it receives?
easy
A. function identity<T>(arg): T { return arg; }
B. function identity(arg: T): T { return arg; }
C. function identity<T>(arg: T): T { return arg; }
D. function identity<T>(arg: T): void { return arg; }

Solution

  1. Step 1: Check generic declaration

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

    The parameter arg should be of type T, and the function should return the same type T.
  3. Final Answer:

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

    Generic function syntax = function identity<T>(arg: T): T { return arg; } [OK]
Hint: Generic type <T> goes before parameters [OK]
Common Mistakes:
  • Omitting <T> before parameters
  • Not specifying type for arg
  • Using void as return type incorrectly
3. What will be the output of the following TypeScript code?
function wrapInArray<T>(value: T): T[] { return [value]; }
const result = wrapInArray(5);
console.log(result);
medium
A. TypeError at runtime
B. 5
C. SyntaxError
D. [5]

Solution

  1. Step 1: Understand function behavior

    The function wrapInArray takes a value of any type T and returns an array containing that value.
  2. Step 2: Analyze the call with number 5

    Calling wrapInArray(5) returns an array with one element: [5].
  3. Final Answer:

    [5] -> Option D
  4. Quick Check:

    wrapInArray(5) = [5] [OK]
Hint: Generic returns array with input inside brackets [OK]
Common Mistakes:
  • Expecting just the value without array
  • Confusing output with error
  • Misreading return type as void
4. Identify the error in this generic function declaration:
function getFirstElement<T>(arr: T): T {
return arr[0];
}
medium
A. Parameter arr should be an array type T[], not T
B. Return type should be T[] instead of T
C. Generic type <T> is missing
D. Function should not use generics here

Solution

  1. Step 1: Check parameter type

    The parameter arr is declared as type T, but the function tries to access arr[0], which requires arr to be an array.
  2. Step 2: Correct parameter type

    To access the first element, arr should be of type T[] (array of T), not just T.
  3. Final Answer:

    Parameter arr should be an array type T[], not T -> Option A
  4. Quick Check:

    Array parameter needs T[] type [OK]
Hint: Array parameters need T[] type, not just T [OK]
Common Mistakes:
  • Using T instead of T[] for arrays
  • Returning wrong type
  • Forgetting to declare generic <T>
5. You want to write a generic function mergeObjects that takes two objects of possibly different types and returns a new object combining both. Which is the correct syntax to declare this function?
hard
A. function mergeObjects(obj1: T, obj2: U): object { return {...obj1, ...obj2}; }
B. function mergeObjects(obj1: T, obj2: U): T & U { return {...obj1, ...obj2}; }
C. function mergeObjects(obj1: object, obj2: object): object { return {...obj1, ...obj2}; }
D. function mergeObjects<T>(obj1: T, obj2: T): T { return {...obj1, ...obj2}; }

Solution

  1. Step 1: Understand the requirement

    The function should accept two objects of different types and return a combined object containing properties of both.
  2. Step 2: Check generic parameters and return type

    Using two generic types T and U allows different input types. The return type T & U means an object with properties from both types.
  3. Step 3: Verify function body

    The spread operator {...obj1, ...obj2} correctly merges the two objects.
  4. Final Answer:

    function mergeObjects<T, U>(obj1: T, obj2: U): T & U { return {...obj1, ...obj2}; } -> Option B
  5. Quick Check:

    Two generics + intersection return = function mergeObjects(obj1: T, obj2: U): T & U { return {...obj1, ...obj2}; } [OK]
Hint: Use two generics and return type intersection T & U [OK]
Common Mistakes:
  • Using same generic type for both parameters
  • Returning just object loses type info
  • Not using intersection type for return
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