TypeScript Using Type Parameters in Generic Constraints
Last Updated :
24 Apr, 2025
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]);