...

/

Constraining Generic Types with Examples

Constraining Generic Types with Examples

Learn how to restrict generic code to a specific set of types using the Concatenator class example.

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:

// 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 ...