Generics in TypeScript can seem daunting at first - what’s with all those capital letters and square brackets? 😅
But don’t worry, this cheat sheet helps demystify Generics and show you how they work with simple examples.
How Generics Works
Generics enable you to define a type variable that serves as a placeholder for a specific type to be provided later. This is the core strength of Generics: they allow you to define flexible, reusable types without sacrificing type safety.
The letter T is commonly used by convention to represent a generic type variable, but you can use any letter or descriptive name that fits your context (other commonly used letters include U, V, K).
Usage examples
Below are some practical examples that demonstrate how Generics work.
You can play with the examples below in this TypeScript playground.
Generics Functions
// A generic function that works with any data type
function identity<T>(arg: T): T {
return arg;
}
// Using the generic function with different types
let num = identity<number>(42); // T is number
let str = identity<string>("Hello"); // T is string
//TS automatically infers the type so this also works:
//let num = identity(42); // T is number
//let str = identity("Hello"); // T is string
In this example, T is a type parameter that can represent any type. The actual type is determined when the function is called, whether it’s a number, string, or any other type.
Here, we've manually set the type to highlight how TypeScript handles different types with generics. However, it's important to remember that TypeScript typically infers the type automatically based on the argument provided. You don't need to manually specify the type unless you're overriding TypeScript's inference or dealing with complex types where explicit type annotations are necessary.
Generic Interfaces
Here, we define an interface Pair with two properties of different types. These types are specified when an instance is created and can be any type. The only constraint is that each property maintains its respective type.
interface Pair<T, K> {
first: T;
second: K;
}
let pair: Pair<string, number> = { first: "one", second: 2 }
let anotherPair: Pair<number, string> = { first: 1, second: "second" }
let otherPair: Pair<number, number> = { first: 1, second: 2 }
Generics Types
Generics can also be applied to custom types. The process is similar to interfaces: you define a shape with placeholder types, which are determined when the type is used. Generics enforce typing but do not dictate specific types.
type Person<T, K, V> = {
name: T,
age: K,
isMarried: V
}
const person1: Person<string, number, boolean> = {
name: 'Bob',
age: 67,
isMarried: false
}
Generic Classes
Generic classes allow you to define a blueprint where the data’s type is flexible, only being defined when an instance is created. In this example, the Box class can store content of any type (for example, a string, a number, or any other type).
class Box<T> {
content: T
constructor(content: T){
this.content = content
}
getContent(): T {
return this.content
}
}
const letterBox = new Box('a')
const numberBox = new Box(1)
Constraints
Generics also support constraints, allowing you to limit the types that can be used. For example, if you only want to support types with a length property, you can enforce this constraint using the extends keyword. It restricts the generic type variable to be a subtype of a particular type or interface. This ensures that the generic type must have certain properties or structure.
type LengthType = {length: number}
function getLength<T extends LengthType>(args: T){
return args.length
}
getLength('abc')
getLength([1, 2])
//this doesn't work:
//getLength(2)
//getLength({"a": "b"})
Utility types
Utility types in TypeScript use generics to create flexible and reusable type transformations. They simplify working with existing types by providing built-in operations.
interface User {
name: string;
age: number;
location: string;
}
//makes all properties optional
const partialUser: Partial<User> = {name: 'Alice'}
//allows to omit properties: here the name property is omitted
const omitUser: Omit<User, 'name'> = {location: 'Berlin', age: 33}
I hope this was helpful!
Feel free to reach out if you have any questions! You can also find me on Github, LinkedIn, and Instagram.