Typescript Generic explained

Last update: 2022-12-01
Quick Win's logo Quick Win
TypeScript TypeScript

In TypeScript, a generic is a way to create a type that is flexible and can work with a variety of data types. You can use generics when you want to write code that is reusable and can work with multiple types, but you don’t want to specify the exact type until the code is used.

To create a generic type, you can use angle brackets (<>) to specify a placeholder for the type. For example, the Array type in TypeScript is a generic type that allows you to create an array of any type:

const numbers: Array<number> = [1, 2, 3];
const strings: Array<string> = ['a', 'b', 'c'];

You can also create your own generic types by using a type parameter. For example, you might create a Pair type that can hold a pair of values of any type:

type Pair<T, U> = [T, U];

const pair: Pair<string, number> = ['hello', 123];

Generics are a powerful feature in TypeScript that can help you write more flexible and reusable code.

Simon Grimm