×

Generics in TypeScript

Shailendra Chauhan  Print   5 min read  
14 May 2022
 
Advanced
3.15K Views

Generics enforce type safety without compromising performance, or productivity. In generics, a type parameter is supplied between the open (<) and close (>) brackets and which makes it strongly typed collections i.e. generics collections contain only similar types of objects.

Generics are a fundamental feature in TypeScript that allows developers to pass types as a parameter to another type, with function, or another type of structure. When we create our component as a generic component, then it assumes that the component has all the ability to accept and implement typing that is being passed in when the component is used further, which eventually improves code flexibility, and allows us to write clean and robust code.

In TypeScript, you can create generic functions, generic methods, generic interfaces, and generic classes.

generic.ts

function doReverse(list: T[]): T[] {
 let revList: T[] = [];
 for (let i = (list.length - 1); i >= 0; i--) {
 revList.push(list[i]);
 }
 return revList;
}
let letters = ['a', 'b', 'c', 'd', 'e'];
let reversedLetters = doReverse(letters); // e, d, c, b, a

let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = doReverse(numbers); // 5, 4, 3, 2, 1

Generic Functions

When a function implementation includes type parameters in its signature then it is called a generic function. A generic function has a type parameter enclosed in angle brackets (< >) immediately after the function name.

The following is an example of a generic function:

genericfunction.ts

function doReverse(list: T[]): T[] {
 let revList: T[] = [];
 for (let i = (list.length - 1); i >= 0; i--) {
 revList.push(list[i]);
 }
 return revList;
}
let letters = ['a', 'b', 'c', 'd', 'e'];
let reversedLetters = doReverse(letters); // e, d, c, b, a

let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = doReverse(numbers); // 5, 4, 3, 2, 1

By using the "T[]", we are instructing that the values being passed have no pre-defined types and it will be identified once it's being used further while calling the function along with the arguments.

Generics are purely compile-time representation; compiled JavaScript code does not have such representation. The compiled JavaScript (ES5) code for the above TypeScript code is given below:

genericfunction.js

function doReverse(list) {
 var revList = [];
 for (var i = (list.length - 1); i >= 0; i--) {
 revList.push(list[i]);
 }
 return revList;
}
var letters = ['a', 'b', 'c', 'd', 'e'];
var reversedLetters = doReverse(letters); 

var numbers = [1, 2, 3, 4, 5];
var reversedNumbers = doReverse(numbers);

Generic Classes

A generic class has a type parameter enclosed in angle brackets (< >) immediately after the class name. In generic class, the same type parameter can be used to annotate method parameters, properties, return types, and local variables.

The following is an example of a generic class:

genericclass.ts

class ItemList
{
 private itemArray: Array;
 constructor() {
 this.itemArray = [];
 }

 Add(item: T) : void {
 this.itemArray.push(item);
 }
 GetAll(): Array {
 return this.itemArray;
 }
}
let fruits = new ItemList();
fruits.Add("Apple");
fruits.Add("Mango");
fruits.Add("Orange");

let listOfFruits = fruits.GetAll();
for (let i = 0; i < listOfFruits.length; i++) {
 console.log(listOfFruits[i]);
}
/* -- Output ---
Apple
Mango
Orange
*/

Generics are purely compile-time representation; compiled JavaScript code does not have such representation. The compiled JavaScript (ES5) code for the above TypeScript code is given below:

genericclass.js

var ItemList = (function () {
 function ItemList() {
 this.itemArray = [];
 }
 ItemList.prototype.Add = function (item) {
 this.itemArray.push(item);
 };
 ItemList.prototype.GetAll = function () {
 return this.itemArray;
 };
 return ItemList;
}());
var fruits = new ItemList();
fruits.Add("Apple");
fruits.Add("Mango");
fruits.Add("Orange");
var listOfFruits = fruits.GetAll();
for (var i = 0; i < listOfFruits.length; i++) {
 console.log(listOfFruits[i]);
}

Generic Interfaces

A generic interface has a type parameter enclosed in angle brackets (< >) immediately after the interface name. In a generic interface, the same type parameter can be used to annotate method parameters, properties, return types, and local variables.

The following is an example of a generic interface:

genericinterface.ts

interface IItemList {
 itemArray: Array;
 Add(item: T): void;
 GetAll(): Array;
}

class ItemList implements IItemList
{
 itemArray: Array;
 constructor() {
 this.itemArray = [];
 }

 Add(item: T): void {
 this.itemArray.push(item);
 }
 GetAll(): Array {
 return this.itemArray;
 }
}

let fruits = new ItemList();
fruits.Add("Apple");
fruits.Add("Mango");
fruits.Add("Orange");

let listOfFruits = fruits.GetAll();
for (let i = 0; i < listOfFruits.length; i++) {
 console.log(listOfFruits[i]);
}
/* -- Output ---
Apple
Mango
Orange
*/

Generics are purely compile-time representation; compiled JavaScript code does not have such representation. The compiled JavaScript (ES5) code for the above TypeScript code is given below:

genericinterface.js

var ItemList = (function () {
 function ItemList() {
 this.itemArray = [];
 }
 ItemList.prototype.Add = function (item) {
 this.itemArray.push(item);
 };
 ItemList.prototype.GetAll = function () {
 return this.itemArray;
 };
 return ItemList;
}());
var fruits = new ItemList();
fruits.Add("Apple");
fruits.Add("Mango");
fruits.Add("Orange");
var listOfFruits = fruits.GetAll();
for (var i = 0; i < listOfFruits.length; i++) {
 console.log(listOfFruits[i]);
}
What do you think?

We have learned about the generics with the classes, interface, functions and can also create generics with custom type. Generics allows us to make generics a powerful weapon we have at our disposal while working with TypeScript. Using the effectiveness of generics may save us from repeating code over and over again, and will make the types we have written more flexible and predictable at last.

I hope you will enjoy the Generics in TypeScript while developing your web app. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Share Article

Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

Learn to Crack Your Technical Interview

Accept cookies & close this