function identity<T>(arg: T): T {
    return arg;
}

console.log(identity<string>("Hello")); // Output: Hello
console.log(identity<number>(42)); // Output: 42
Bash

Explanation:

  • This program demonstrates the use of generics, allowing the identity function to work with any data type.
  • The type T is a placeholder for the type of the argument passed to the function.
  • The function returns the same type as the argument, ensuring type safety.
Resize text
Scroll to Top