Introduction
Typescript is a programming language that Microsoft developed. It is like a superset of the more commonly used Javascript. Typescript is designed for the development of very large-scale applications. Since it is a superset of Javascript, existing Javascript programs are also valid in Typescript. Typescript files are saved with the .ts extension.
Generics is a Typescript tool that provides the user ways to create reusable components. Generics make components that allow the user to work with various data types. Generics ensures that the Typescript program is scalable for long-term use and makes sure it is flexible.
Let us look at an example of Generics to understand it better,
function numberOrString<T>(toCheck: T): T {
return toCheck;
}
let name = numberOrString<string>("CodingNinja");
let num = numberOrString<number>( 1001 );
console.log(name+ ", Type of variable is : " +typeof(name));
console.log(num+ ", Type of variable is : " +typeof(num));
To create a Generic Type function, we add the open and close angular brackets (<>) in front of the function name and pass a variable in the brackets. In our case, we have used T. In the above code snippet for the variable “name,” the input and return type of the function is a string, and for the variable “num,” the input and return type of the function is a number.
Why Generics are Important
Let us look at an example to understand the importance of Generics in Typescript,
function pushItems(items: any[] ) : any[] {
return new Array().concat(items);
}
let NumArr = pushItems([1, 2, 3]);
let StrArr = pushItems(["Welcome", "Ninja"]);
NumArr.push(4);
NumArr.push("Hello");
StrArr.push("Hello Ninja");
StrArr.push(4);
console.log(NumArr);
console.log(StrArr);
In the above example, we have used any data type instead of Generics, but what if we only wanted the number values in NumArr and only string values in the StrArr. That’s where Generics come into action. Let’s see how we could have approached this task using Generics.
function pushItems<T>(items:T[]) : T[] {
return new Array<T>().concat(items);
}
let NumArr = pushItems<number>([1, 2, 3]);
let StrArr = pushItems<string>(["Welcome", "Ninja"]);
NumArr.push(4);
NumArr.push("Abcd");
StrArr.push("Hello Ninja");
StrArr.push(50);
console.log(NumArr);
console.log(StrArr);
As is clear from the above example, using Generics, we can restrict the addition of a string value to the NumArr and a number value to the StrArr.
function pushItems<T>(items:T[]) : T[] {
return new Array<T>().concat(items);
}
let NumArr = pushItems<number>([1, 2, 3]);
let StrArr = pushItems<string>(["Welcome", "Ninja"]);
NumArr.push(4);
StrArr.push("Hello Ninja");
console.log(NumArr);
console.log(StrArr);