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);
Explanations:
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.
Output:
"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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/typescript-exercises/typescript-advance-types-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics