Generics Typescript
Posted on November 2, 2024 (Last modified on May 26, 2025) • 3 min read • 433 wordsVideo is in Swedish
TypeScript, a statically typed JavaScript superset, provides a powerful feature called generics to create reusable and flexible code. Generics allow developers to define functions, classes, or interfaces that can work with multiple data types without compromising type safety.
Generics are a way to parameterize types in TypeScript. This means you can define a function or class that takes one or more type parameters, which can be used within the implementation. The type parameters are replaced with actual types when the generic is instantiated.
Here’s an example of a generic function that takes two type parameters, T
and U
, and returns the sum of two values:
function add<T, U>(a: T, b: U): T | U {
return a + b;
}
In this example, add
is a generic function that takes two type parameters, T
and U
. The function returns the sum of two values of types T
and U
, respectively. When you call the function with specific types, TypeScript infers the correct return type:
const result1 = add<number, string>(10, 'hello'); // result1: number | string
const result2 = add<string, boolean>('world', true); // result2: string | boolean
Here’s an example of a generic class that takes one type parameter, T
, and provides a method to create a new instance:
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
In this example, Container
is a generic class that takes one type parameter, T
. The class provides a method to create a new instance with a value of type T
, and returns the value through the getValue
method:
const container = new Container<string>('hello'); // container: Container<string>
const value = container.getValue(); // value: string
Generics in TypeScript provide a powerful way to create reusable, flexible, and type-safe code. By understanding how to use generics effectively, you can write more robust and maintainable software applications. Whether you’re working with functions or classes, generics offer a way to abstract away specific types and focus on the logic of your code.
I hope this article has helped you understand the basics of generics in TypeScript. Happy coding!
Swedish