Open In App

TypeScript Using Type Parameters in Generic Constraints

TypeScript Generics allows you to write reusable code that works with different types. In this article, we will explore how to use type parameters in generic constraints to ensure that which types are allowed in generic types or functions.

Syntax:

function functionName<Type extends ConstraintType>(arg: Type): ReturnType {
    // Function implementation
}

Where:



Example 1: The `logLength` function takes an input object that implements the `Lengthy` interface (i.e., has a `length` property), and it logs the length of that object to the console. It demonstrates how TypeScript can use generics and interfaces to enforce type constraints and provide type safety when working with different types of objects.






interface Lengthy {
    length: number;
}
  
function logLength<T extends Lengthy>(input: T): void {
    console.log(`Length: ${input.length}`);
}
  
// Output: Length: 17
logLength("Hello, TypeScript");
// Output: Length: 5
logLength([1, 2, 3, 4, 5]);

Output:

Output

Example 2: In this example the code demonstrates the creation of two separate queues—one for numbers and one for strings—using TypeScript’s generics, ensuring type safety for the elements stored in each queue.




class Queue<T extends number | string> {
    private items: T[] = [];
  
    enqueue(item: T): void {
        this.items.push(item);
    }
  
    dequeue(): T | undefined {
        return this.items.shift();
    }
}
  
const numberQueue = new Queue<number>();
numberQueue.enqueue(1);
numberQueue.enqueue(2);
  
// Output: 1
console.log(numberQueue.dequeue());
  
const stringQueue = new Queue<string>();
stringQueue.enqueue("Hello");
stringQueue.enqueue("World");
  
// Output: Hello
console.log(stringQueue.dequeue());

Output:

Output

Conclusion: In this article we have discussed Using Type Parameters in Generic Constraints and it’s syntax. And both examples, TypeScript enforces the constraints, providing type safety and preventing potential runtime errors. This allows you to write more reliable and maintainable code when working with generic types in TypeScript.

Reference: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-type-parameters-in-generic-constraints


Article Tags :