Constraining Generic Types with Examples
Learn how to restrict generic code to a specific set of types using the Concatenator class example.
We'll cover the following...
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 stringclass Concatenator<T extends Array<string> | Array<number>> {// Method that concatenates the array of items into a stringpublic concatenateArray(items: T): string {// Initialize an empty string to store the concatenated valueslet returnString = "";// Loop through each item in the arrayfor (let i = 0; i < items.length; i++) {// If this is not the first item, add a comma before appending the valuereturnString += i > 0 ? "," : "";// Append the current value to the return stringreturnString += items[i].toString();}// Return the final concatenated stringreturn returnString;}}
Limiting the type of T
-
We have defined a class named
Concatenator
that is using generic syntax and is also constraining the type ofT
to be either an array of strings or an array of numbers via the ...