DEV Community

Aaron
Aaron

Posted on

2 1

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"];
arr[0].indexOf("s");
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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs