TypeScript generic function example

TypeScript Advance Types: Exercise-9 with Solution

Write a TypeScript generic function that accepts an argument of any type and returns the same value. Test the function with various data types.

Sample Solution:

TypeScript Code:

// Generic function 'identity' that accepts an argument of any type and returns the same value
function identity<T>(arg: T): T {
 return arg;
// Test the 'identity' function with various data types
const num: number = 100;
const str: string = "TypeScript!";
const bool: boolean = true;
const arr: number[] = [1, 2, 3];
const obj: { key: string } = { key: "value" };
const resultNum: number = identity(num);
const resultStr: string = identity(str);
const resultBool: boolean = identity(bool);
const resultArr: number[] = identity(arr);
const resultObj: { key: string } = identity(obj);
console.log("Result for num: " + resultNum);
console.log("Result for str: " + resultStr);
console.log("Result for bool: " + resultBool);
console.log("Result for arr: " + resultArr);
console.log("Result for obj: " + resultObj);


In the exercise above -

  • First, we define a generic function "identity()" that uses a type parameter 'T'. This allows the function to accept arguments of any type.
  • The function "identity()" simply returns the argument 'arg' of type 'T'.
  • Test the "identity()" function with various data types, including numbers, strings, booleans, arrays, and objects.
  • Declare variables with specific types (num, str, bool, arr, obj) and call the "identity()" function with these variables. TypeScript infers the correct return types for each call based on the argument types.
  • Finally, print the results to the console to demonstrate that the function returns the same value with the correct types.


"Result for num: 100"
"Result for str: TypeScript!"
"Result for bool: true"
"Result for arr: 1,2,3"
"Result for obj: [object Object]"

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.

Previous: Calculating length of strings in TypeScript.
Next: TypeScript generic swap function example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.