How to use Type constraints In Typescript
You can specify constraints on the type parameter to ensure that only certain types are accepted.
Syntax:
function functionName<T>(parameter1: T, parameter2: T, ...): ReturnType {
// Function body
}
Example: The type constraint { length: number } ensures that only objects with a length property of type number can be passed to the printLength function. This prevents runtime errors by catching invalid types at compile time.
function printLength<T extends { length: number }>
(obj: T): void {
console.log("Length:", obj.length);
}
printLength("hello");
printLength([1, 2, 3]);
printLength({ length: 5, width: 3 });
printLength(123);
Output:
Length: 5
Length: 3
Length: 5
Error: Type 'number' does not have a property 'length'
How to Create TypeScript Generic Function with Safe Type Matching ?
In TypeScript, generic functions offer a powerful tool for creating flexible and reusable code that can work with various data types. However, ensuring type safety is crucial to prevent runtime errors and maintain code reliability.