DEV Community


Posted on

TypeScript Generics Simply Put

Generics are a really cool feature of any language that supports them. They allow you to write more abstracted code while maintaining the type safety/hinting that you CRAVE.

If you've used TypeScript at all, you've likely already encountered Generics through Arrays. When you create a variable that is of type array, it looks like this.

const arr: Array = []; 
Enter fullscreen mode Exit fullscreen mode

However, this isn't valid on its own, as TypeScript is expecting to know what type will populate this array. We denote this type using angle brackets <>.

const arr: Array<any> = [];
Enter fullscreen mode Exit fullscreen mode

Of course, using any just tells TypeScript to expect all types of data.

But now let's say you are expecting to fill this array with strings so that you can call the indexOf method on any element. You can change any to string and TypeScript will then know what methods will be available.

const arr: Array<string> = ["some", "strings"];
Enter fullscreen mode Exit fullscreen mode

Using the same angle bracket syntax, you add the Generic type to a function signature, class or interface. The convention is to use a capital T, that simply abbreviates "type." Then you typically pass this type as an argument type in a constructor, method or function.

The Array interface in its simplest form could be written this way...

interface Array<T> {
    (arg: T): T;
Enter fullscreen mode Exit fullscreen mode

This allows any type to be associated with an Array type. We could store Objects, Maps, Atomic, Proxy, Numbers, anything!

Generics are a really powerful way of abstracting code so that it's not super specific to one type of data.

Read more about Generics in the TypeScript docs.

Top comments (0)