0
0
Typescriptprogramming~5 mins

Multiple generic parameters in Typescript

Choose your learning style9 modes available
Introduction

Using multiple generic parameters lets you write flexible code that works with different types at the same time.

When you want a function to accept two different types and relate them.
When creating a class that handles pairs of values with different types.
When you want to write reusable code that works with multiple types without repeating.
When you want to keep type safety while working with different data types together.
Syntax
Typescript
function example<T, U>(param1: T, param2: U): void {
  // function body
}

You separate multiple generic parameters with commas inside angle brackets <>.

Each generic parameter can be used independently in the function or class.

Examples
This function takes two different types and returns a string combining them.
Typescript
function pairToString<T, U>(first: T, second: U): string {
  return `${first} and ${second}`;
}
This class stores a key and a value with different types and shows them.
Typescript
class KeyValue<K, V> {
  constructor(public key: K, public value: V) {}

  display(): string {
    return `Key: ${this.key}, Value: ${this.value}`;
  }
}
Sample Program

This program defines a function with two generic types. It prints a description using both types.

Typescript
function describePair<T, U>(item1: T, item2: U): string {
  return `First item is ${item1}, second item is ${item2}`;
}

const result = describePair<number, string>(42, "apples");
console.log(result);
OutputSuccess
Important Notes

You can use as many generic parameters as you need, but keep it simple to avoid confusion.

Generic parameters help keep your code safe by checking types before running.

Summary

Multiple generic parameters let you work with different types together.

They make your code reusable and type-safe.

Use angle brackets <> with commas to list multiple generics.