Building Generic Classes and Components

Tutorial 4 of 5

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.