This content originally appeared on DEV Community and was authored by Audrey Kadjar
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
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.
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: both properties cannot be of the same 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" }
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.
This content originally appeared on DEV Community and was authored by Audrey Kadjar
Audrey Kadjar | Sciencx (2024-08-15T16:17:19+00:00) 🛠️ 📦 TypeScript Generics – a cheat sheet. Retrieved from https://www.scien.cx/2024/08/15/%f0%9f%9b%a0%ef%b8%8f-%f0%9f%93%a6-typescript-generics-a-cheat-sheet/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.