In TypeScript,
generics allow you to create functions, classes, and interfaces that can work with a variety of types rather than a single specific type. This makes your code more reusable and flexible.
To use generics in TypeScript, you use the angle bracket notation `< >` to define a placeholder type that will be replaced with a concrete type when the code is used. Here's an example of a simple generic function that returns the first element of an array:
function getFirst(arr: T[]): T | undefined {
return arr.length > 0 ? arr[0] : undefined;
}
In this example, the function is defined with the generic type parameter `T`, which is used to declare the type of the array. The function returns the first element of the array, which has the same type as the elements in the array.
To use this function, you call it with an array of a specific type:
let numbers: number[] = [1, 2, 3];
let firstNumber = getFirst(numbers);
Here, the `numbers` array has the type `number[]`, so the generic type parameter `T` in the `getFirst` function is inferred as `number`. The return value of the function is `number | undefined`, which means it can be either a number or undefined if the array is empty.
You can also explicitly specify the type parameter when calling the function:
let strings: string[] = ["foo", "bar", "baz"];
let firstString = getFirst(strings);
In this case, the generic type parameter `T` is explicitly set to `string`, so the return value of the function is `string | undefined`.
Generics can also be used with classes and interfaces to create generic types that can work with a variety of types. For example, here's a simple interface that defines a generic `Box` type:
interface Box {
value: T;
}
This interface defines a `Box` type that has a single property `value` of type `T`. When you create an instance of `Box`, you can specify the concrete type of `T`:
let numberBox: Box = { value: 42 };
let stringBox: Box = { value: "hello" };
In this example, `numberBox` has the type `Box` and `stringBox` has the type `Box`.