TypeScript / TypeScript Generics

Building Generic Classes and Components

This tutorial will take you through the process of creating generic classes and components in TypeScript. These generic components will provide flexibility in handling a variety o…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explains how to use generics to create reusable and type-safe components in TypeScript.

Building Generic Classes and Components

1. Introduction

Goal of The Tutorial

This tutorial aims to guide you through the process of building generic classes and components in TypeScript.

What You Will Learn

You will learn how to create flexible, reusable classes and components that can handle a variety of data types.

Prerequisites

  • Basic understanding of TypeScript
  • Familiarity with Object-Oriented Programming (OOP) concepts

2. Step-by-Step Guide

What are Generics?

In TypeScript, Generics promote code reusability while keeping type safety. They are like the placeholders for any data type that gets determined at the time of function invocation or class instance creation.

Generic Classes

A generic class has a similar shape to a generic interface. A generic class has a generic type parameter list in angle brackets (<>) following the name of the class.

class GenericClass<T> {
    value: T;
    add: (x: T, y: T) => T;
}

In the above code, T is a type variable—a kind of variable that works on types rather than values.

Best Practices and Tips

  • Use generics when you want to create reusable components that can work over a variety of types rather than a single one.
  • Always use meaningful names for your type variables.

3. Code Examples

Example 1: Generic Class with number type

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

console.log(myGenericNumber.add(3, 4));

In this example, we create an instance of GenericNumber for number type. The add function is provided which takes two arguments of type T and returns a value of type T.

Expected output: 7

Example 2: Generic Class with string type

let stringNumeric = new GenericNumber<string>();
stringNumeric.zeroValue = "";
stringNumeric.add = function(x, y) { return x + y; };

console.log(stringNumeric.add(stringNumeric.zeroValue, "test"));

Here, we're creating a class with string type. The add function concatenates two strings.

Expected output: test

4. Summary

  • Introduced to the concept of Generics in TypeScript and their usage in promoting code reusability.
  • Created generic classes with different data types and understood how they offer flexibility.
  • Explored best practices while working with generics.

Next Steps for Learning

Continue exploring more advanced topics in TypeScript like Generic Constraints, Default values in Generics and using multiple type variables in Generics.

Additional Resources

5. Practice Exercises

Exercise 1

Create a generic class KeyValuePair that contains key-value pairs of any type.

Exercise 2

Create a generic function that accepts an array of any type and prints each element.

Solutions

// Solution to Exercise 1
class KeyValuePair<T, U> {
    private key: T;
    private val: U;
    setKeyValue(key: T, val: U) {
        this.key = key;
        this.val = val;
    }
    display() {
        console.log(`key = ${this.key}, val = ${this.val}`);
    }
}

// Solution to Exercise 2
function printArray<T>(items : T[] ) : void {
    for(let i = 0; i<items.length; i++) {
        console.log(items[i]);
    }
}

Tips for Further Practice

Try to implement a generic stack or queue data structure, and work with more complex data types.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help