OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Keeping Your TypeScript Code DRY With Generics

Samaila Bala
May 11th, 2021 · 5 min read

JavaScript has become popular over the years, with the increase in popularity you have more developers migrating from other strongly typed programming languages complaining about the loosely-typed nature of JavaScript and that brings us to TypeScript.

TypeScript is an open-source programming language that is a superset of JavaScript. It builds on top of JavaScript by adding statically typed definitions. This gives developers assurance over code written as it saves time catching errors before a code is executed.

In this article, we will be looking at one of the important concepts of TypeScript called Generics and how it helps developers in following the Don’t-Repeat-Yourself (DRY) principle.

This article assumes you have a basic knowledge of TypeScript to follow along. You can brush up on the basics here. You also need the following tools below to install TypeScript on your machine:

  • Node v12 or greater
  • npm v5.2 or greater
  • A code editor
  • A Terminal

Installing TypeScript

To get started with TypeScript open a terminal and run the code below to create a directory for the project:

1mkdir typescript-generics-example

Navigate to the project directory

1cd typescript-generics-example

Run the code below to create a package.json file

1npm init -y

Install the TypeScript library by running the code below

1# using npm
2npm install --global typescript # Global installation
3npm install --save-dev typescript # Local installation

Create a tsconfig.json file

1tsc --init

The command above creates a tsconfig.json file in your project directory. The tsconfig.json file specifies the root files and the compiler options required to compile the project.

To test our setup create a file app.ts in the root directory and paste the code below

1function showMessage(name: string) {
2 console.log('Hello ' + name);
3}
4showMessage('Sama');

Now go to package.json and modify the script property to be similar to the code below

1"scripts": {
2 "dev": "tsc app.ts && node app.js && rm -rf app.js"
3},

The dev command transpiles TypeSript to JavaScript before executing and then removes the JavaScript file after execution.

Open a terminal, navigate to the root directory of the project and run the code below to run the script

1npm run dev

You should get “Hello Sama” as output in your terminal.

What are Generics?

Generics have been a major feature of strongly typed languages like Java and C#. In TypeScript, they allow the types of components and functions to be specified later which allows them to be used in creating reusable components that can apply to different use cases, for example:

1function returnInput <Type>(arg: Type): Type {
2 return arg;
3};
4const returnInputStr = returnInput<string>('Foo Bar');
5const returnInputNum = returnInput<number>(5);
6
7console.log(returnInputStr); // Foo Bar
8console.log(returnInputNum); // 5

In the example above, I created a generic function that returns the user input. When calling the function I made sure it is type-safe by specifying the type at the point of execution. This way the function is reusable for a different use case but also checks to make sure the type specified is returned.

The Problem

There are times when you want to create a function or component for multiple use cases like the example below:

1type TodoItem = { taskId: number; task: string | number; done: boolean };
2
3let id: number = 0;
4let todoList: Array<TodoItem> = [];
5
6function printTodos(): void {
7 console.log(todoList);
8}
9function addTodo(item: string): void {
10 todoList.push({ taskId: id++, task: item, done: false });
11}
12function addTodoNumber(item: number): void {
13 todoList.push({ taskId: id++, task: item, done: false });
14}
15
16addTodo('Learn TypeScript');
17addTodoNumber(22);
18printTodos();

In the code snippet we are trying to add two different types of todo items to the todoList array, because of the different types we have to create two different functions to add todoItemsto the todoList. This violates the Don’t-Repeat-Yourself (DRY) principle which states that “Every piece of knowledge or logic must have a single, unambiguous representation within a system”. In this case, the two functions have the same implementation with just different types.

An alternative to duplication can be done by using the any type

1type TodoItem = { taskId: number; task: string | number; done: boolean };
2
3let id: number = 0;
4let todoList: Array<TodoItem> = [];
5
6function printTodos(): void {
7 console.log(todoList);
8}
9function addTodo(item: any): void {
10 todoList.push({ taskId: id++, task: item, done: false });
11}
12
13addTodo('Learn TypeScript');
14addTodo(22);
15printTodos();

This makes sure we adhere to the DRY principle but introduces another problem. Using any datatype means we accept any type, which in turn means we aren’t controlling the type accepted and returned, thus invalidating the benefits of using types in our code.

In the next section, we will look at how to adhere to the DRY Principle by making sure our solution is generic and type-safe by controlling the type of data accepted and returned.

Using Generics to solve the problem

Now that we’ve established what Generics are and why they are needed let’s see how we can use them to solve the problem stated in the previous section.

1let id: number = 0;
2let todoList = [];
3function printTodos(): void {
4 console.log(todoList);
5}
6function addTodo<Type>(item: Type): void {
7 todoList.push({ taskId: id++, task: item, done: false });
8}
9addTodo<string>('Learn TypeScript');
10addTodo<number>(22);
11printTodos();

In the solution above we’ve made the function addTodo we created earlier, Generic. The <Type> is a placeholder that will be replaced by the type when we run the function and it ensures the function is type-safe e.g addTodo<string>('Sama'); declares the type as a string so if the parameter passed to the function isn’t a string it’ll result in an error.

Generic functions also allow us to pass default types to the function definition. This helps define a default behavior if we want to avoid having to declare the type every time we use the function.

1function addTodo<Type = string>(item: Type): void {
2 todoList.push({ taskId: id++, task: item, done: false });
3}
4addTodo('Learn TypeScript');

So far, we’ve looked at creating generic functions with just one parameter. What if the function has multiple parameters of different types?

1let id: number = 0;
2let todoList = [];
3
4function printTodos(): void {
5 console.log(todoList);
6}
7function addTodo<T, S>(item: T, status: S): void {
8 todoList.push({ taskId: id++, task: item, done: status });
9}
10
11addTodo<string, boolean>('Learn TypeScript', true);
12addTodo<number, boolean>(22, false);
13printTodos();

We can solve this by passing multiple parameters as placeholders <T,S> to the generic function definition and then specifying what type belongs to an argument (item: T, status: S). Lastly, when we run the function we can now replace the placeholders defined with the correct types addTodo<string, boolean>('Learn TypeScript', true).

Generic Classes

We can also make classes Generic. Let’s create a Todo class to show how this works

1let id: number = 0;
2type TodoListItem = {
3 taskId: number;
4 task: string;
5 done: boolean;
6}
7class Todo<Type> {
8 _todoList: Array<Type> = [];
9 addTodo(item: Type): void {
10 this._todoList.push(item);
11 }
12 printTodos(): void {
13 console.log(this._todoList);
14 }
15}
16const Todos = new Todo<TodoListItem>();
17Todos.addTodo({ taskId: id++, task: 'learn TypeScript', done: true });
18Todos.addTodo({ taskId: id++, task: 'Practice TypeScript', done: false });
19Todos.printTodos();

Generic classes are similar to Generic functions the major difference is in how they are used. Generic classes take a type parameter when they are instantiated new Todo<TodoItem>(); while Generic functions take a Type parameter at the point of execution:addTodo<string>('Sama').

Generic Constraints

While Generic functions and classes make sure we adhere to the DRY principle it also gives rise to some questions we will look at below:

  1. What if we want to limit a Generic function to certain types?

When a function is Generic it means it can be used in any form and also accept any type. For example

1addTodo<boolean>(true);

But what if we want to use the generic function for strings and numbers but not boolean. How do we go about it?

To do so we’ll use the extends keyword and specify the types we want to constrain the function to as specified in the example below

1function addTodo<Type extends string | number>(item: Type): void {
2 todoList.push({ taskId: id++, task: item, done: false });
3}

From the solution above we’ve made sure this generic function will only accept types of number and string and nothing else. This means when you try to execute the boolean example showed it’ll result in an error as boolean wasn’t part of the type constraint.

  1. What if our function implementation doesn’t support a particular Type?

Let’s imagine we have a function that returns the length of the todoList

1function getTodoListLength<Type>(arr: Type): void {
2 console.log(arr.length);
3}

If we try to execute this function with types that don’t have support for the length attribute (like number) it will result in an error.

To solve this problem we can also make use of the extends keyword to constrain the types to what the implementation supports as shown below

1function getTodoListLength<Type extends Array<TodoItem>>(arr: Type): void {
2 console.log(arr.length);
3}
4getTodoListLength<Array<TodoItem>>(todoList);

Measuring front-end performance

Monitoring the performance of a web application in production may be challenging and time-consuming. OpenReplay is an open-source session replay stack for developers. It helps you replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder.

OpenReplay lets you reproduce issues, aggregate JS errors and monitor your app’s performance. OpenReplay offers plugins for capturing the state of your Redux or VueX store and for inspecting Fetch requests and GraphQL queries.

OpenReplay Redux

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

Conclusion

In this article, we’ve looked at how to use TypeScript Generics to write reusable functions and classes that respect the DRY principle. We’ve also looked at how to get around Generic constraints by using the extends keyword. While Generics might be difficult to understand the aim of this article was to make it less complex by using relatable examples so you’ll be able to practice and apply them in your applications.

More articles from OpenReplay Blog

The Complete Guide to Google's Core Web Vitals Performance Metrics

Content, keywords, and backlinks are important search ranking factors. However, compare two sites with similar content and target markets: the one with the best web experience should rank higher.

April 28th, 2021 · 7 min read

Functional Reactive Programming in Angular with RxJS

Reactive Programming is not exclusive to ReactJS, learn how to use RFP with Angular

April 27th, 2021 · 11 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552