Typescript Generics Explained

Learn what generics are and how they are used in Typescript

Ross Bulat
11 min readApr 20, 2019

Generics: the ability to abstract types

The implementation of generics in Typescript give us the ability to pass in a range of types to a component, adding an extra layer of abstraction and re-usability to your code. Generics can be applied to functions, interfaces and classes in Typescript.

This talk will explain what generics are and how they can be used for these items, visiting a range of viable use cases along the way to further abstract your code.

The Hello World of Generics

To demonstrate the idea behind generics in simple terms, consider the following function, identity(), that simply takes one argument and returns it:

function identity(arg: number): number {
return arg;
}

Our identity function’s purpose is to simply return the argument we pass in. The problem here is that we are assigning the number type to both the argument and return type, rendering the function only usable for this primitive type — the function is not very expandable, or generic, as we would like it to be.

We could indeed swap number to any, but in the process we are losing the ability to…

--

--

Ross Bulat
Ross Bulat

Written by Ross Bulat

Programmer and Author. @ Parity Technologies, JKRB Investments

Responses (14)