Search⌘ K
AI Features

Constraining Generic Types with Examples

Understand how to constrain generic types in TypeScript using the extends keyword to enforce type safety. Learn through practical examples how to restrict generics to arrays of strings or numbers, ensuring your code handles only intended data types while avoiding misuse.

Constraining the type of T

In most instances, we will want to limit the type of T in order to only allow a specific set of types to be used within our generic code. This is best explained through an example as follows:

TypeScript 4.9.5
// This class takes an array of strings or numbers and concatenates them into a single string
class Concatenator<T extends Array<string> | Array<number>> {
// Method that concatenates the array of items into a string
public concatenateArray(items: T): string {
// Initialize an empty string to store the concatenated values
let returnString = "";
// Loop through each item in the array
for (let i = 0; i < items.length; i++) {
// If this is not the first item, add a comma before appending the value
returnString += i > 0 ? "," : "";
// Append the current value to the return string
returnString += items[i].toString();
}
// Return the final concatenated string
return returnString;
}
}
Limiting the type of T
  • We have defined a class named Concatenator that is using generic syntax and is also constraining the type of T to be either an array of strings or an array of numbers via the ...