TypeScript Generics Tutorial
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
Learn about TypeScript generics and how to use them to create reusable functions and classes.
Introduction to Generics
In TypeScript, generics are a way to create reusable functions and classes that can work with multiple types. They allow you to define a type parameter that can be specified when the function or class is used.
Step 1: Define a Generic Function
Create a new file called utils.ts and add the following code:
function first<T>(arr: T[]): T {
return arr[0];
}
This code defines a generic function called first that takes an array of type T and returns the first element of the array.
Step 2: Use the Generic Function
Create a new file called main.ts and add the following code:
const numbers = [1, 2, 3];
const firstNumber = first(numbers);
console.log(firstNumber);
const strings = ['a', 'b', 'c'];
const firstString = first(strings);
console.log(firstString);
This code uses the first function to get the first element of an array of numbers and an array of strings.
Step 3: Define a Generic Class
Add the following code to the utils.ts file:
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
This code defines a generic class called Container that has a private property value of type T and a method getValue that returns the value.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based TypeScript courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for TypeScript books — check the publication year so the examples match current versions.
Search Amazon →