Learn TypeScript

Introduction

Introduction

Generics

TypeScript generics allows us to create strongly-typed functions, classes, and data structures that can be used with different types.

Consider the function below that returns the first element in an array, or null if the array is empty:

function firstOrNull(array: string[]): string | null {
return array.length === 0 ? null : array[0];
}

This function can only operate with string based arrays though. If we wanted the function to operate with numerical arrays we could add a new function as follows:

function firstOrNullInNumberArray(array: number[]): number | null {
return array.length === 0 ? null : array[0];
}

... but we are duplicating the implementation.

We could use the any type:

function firstOrNull(array: any[]): any | null {
return array.length === 0 ? null : array[0];
}

... but we have lost the strong typing.

This is the problem that generics solves. It allows type annotations to be based on parameters so that the implementation isn't dependent on a specific type.

Generics allow us to write reusable, flexible, and extensible functions, classes, and data structures while maintaining strong typing.

We will start this module by learning to use to some standard generic types in TypeScript before learning how to create our own generic functions, classes, interfaces, and type aliases. We will learn how to specify default types for a generic parameter and how to contain generic parameters. We will also learn how to use generic types with the rest and spread syntax.

In this module we will cover:

© 2023 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more