Open In App

TypeScript Using Type Parameters in Generic Constraints

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • <Type> is a type parameter
  • extends will extend the types to the function
  • ConstraintType represents the type or set of type that ‘Type’ must adhere it. This constraint ensures that the generic type ‘Type’ satisfies certain conditions or has specific properties.
  • (arg: Type) is the Function parameter list. Here we are specifying that the function takes an argument ‘arg’ of type ‘Type’.

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.

Javascript




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:

Screenshot-(1073)

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.

Javascript




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:

Screenshot-(1072)

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads