Menu
Coddy logo textTech

Creating Generic Identity Func

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 58 of 73.

Here's the syntax for a generic function using the classic identity example:

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

The <T> after the function name declares a type parameter called T. This T acts as a placeholder that can represent any type. When you use this function, TypeScript will replace T with the actual type you're working with.

The beauty of this approach is that it preserves type information.

If you call identity("hello"), TypeScript knows the return type is string. If you call identity(42), it knows the return type is number.

You get all the flexibility of working with multiple types while keeping full type safety.

By convention, T stands for "Type," but you can use any name you want for your type parameter. The important thing is that it creates a relationship between the input and output types of your function.

challenge icon

Challenge

Easy

Create a generic function named wrapInObject that takes an argument of any type and returns an object containing that value.

The function should:

  • Use a generic type parameter T
  • Accept one parameter named item of type T
  • Return an object with a single property value of type T
  • Have an explicit return type annotation

Create the following variables to test your function:

  • wrappedString - call wrapInObject with the string "Hello TypeScript"
  • wrappedNumber - call wrapInObject with the number 42
  • wrappedBoolean - call wrapInObject with the boolean true

Print the following outputs:

  • Print wrappedString.value
  • Print wrappedNumber.value
  • Print wrappedBoolean.value
  • Print the result of calling wrapInObject with the string "Generic", accessing the value property
  • Print the result of calling wrapInObject with the number 100, accessing the value property

Try it yourself

// TODO: Write your code here
// Create the generic function wrapInObject

// TODO: Create the test variables
// wrappedString, wrappedNumber, wrappedBoolean

// Print the outputs
console.log(wrappedString.value);
console.log(wrappedNumber.value);
console.log(wrappedBoolean.value);
console.log(wrapInObject("Generic").value);
console.log(wrapInObject(100).value);
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript