Menu
Coddy logo textTech

Using a Generic Function

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

There are two ways to use a generic function: with explicit type arguments or by letting TypeScript infer the type automatically.

Here's how you can call a generic function with explicit type arguments:

const result1 = wrapInObject("hello");
const result2 = wrapInObject(42);

The <string> and <number> explicitly tell TypeScript what type to use for T. This gives you complete control over the type parameter.

However, TypeScript is smart enough to infer the type from the argument you pass in most cases:

const result1 = wrapInObject("hello");  // T inferred as string
const result2 = wrapInObject(42);       // T inferred as number

Type inference makes your code cleaner and more readable while maintaining the same type safety. TypeScript analyzes the argument and automatically determines what T should be, so you don't need to write the explicit type annotation unless you want to override the inferred type.

challenge icon

Challenge

Easy

You are provided with the following from the previous challenge:

  • The generic function wrapInObject<T> that takes an item of type T and returns { value: T }

Call the wrapInObject function using both explicit type arguments and type inference:

Using explicit type arguments:

  • Create a variable explicitString by calling wrapInObject<string> with "TypeScript"
  • Create a variable explicitNumber by calling wrapInObject<number> with 25
  • Create a variable explicitBoolean by calling wrapInObject<boolean> with false

Using type inference:

  • Create a variable inferredString by calling wrapInObject with "Generics" (let TypeScript infer the type)
  • Create a variable inferredNumber by calling wrapInObject with 99 (let TypeScript infer the type)
  • Create a variable inferredBoolean by calling wrapInObject with true (let TypeScript infer the type)

Print the following outputs:

  • Print explicitString.value
  • Print explicitNumber.value
  • Print explicitBoolean.value
  • Print inferredString.value
  • Print inferredNumber.value
  • Print inferredBoolean.value

Try it yourself

// Generic function from previous challenge
function wrapInObject<T>(item: T): { value: T } {
    return { value: item };
}

// TODO: Write your code here
// Create variables using explicit type arguments
// Create variables using type inference

// Print the results
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