###### Table of Contents
- [[]]
- [[]]
- [[]]
- [[]]
#### [[TypeScript Basics#Generics]]
# Generic functions
Arrays are generic data types: they can hold any type of data. What if we want to write a function that works on any type of data?
We can define _generic functions_ using the same `<>` syntax. When a function is generic, it has a "type hole", just like `Array` does.
The hole must be filled by a type, like how `number` fills `Array<number>`
In the example below, we name the type hole `T`. This is a common generic type parameter name, and it works well enough in simple situations.
We named our generic type parameter `T`, which is a very common name. There's nothing special about that name; we can use any name we like. Type parameters should be UpperCamelCased, though, like all types that we define.
This convention makes it easy for us to tell a `User` type from a `user` variable.
```ts
function first<T>(elements: Array<T>): T {
return elements[0];
}
first<boolean>([true, false]);
```
(Our function deals with arrays of elements. We named our type variable `T`, and you'll see a lot of real-world code and examples using that name. However, `Element` is probably a better type name than `T`. `Element` is a bit more specific: it's the type of the array elements.)
We fill the type hole when we *call* the function.
For example, `first<boolean>` fills the type hole with `boolean`. Let's trace the `boolean` type's path through the function, imagining what the compiler is doing. At each step, it replaces the `T` type parameter with the actual type.
1. The `boolean` in our function call fills the type hole `T` in the `first<T>` function definition.
2. The argument `(elements: Array<T>)` becomes `(elements: Array<boolean>)`.
3. The return type of `first` is `T`, which is still `boolean`, so `first<boolean>` returns a `boolean`.
4. Finally, all of the types match, so the function type checks
```ts
function first(elements: Array<boolean>): boolean {
return elements[0];
}
first([true, false]);
```
The type parameters can vary every time we use the function: `first<string>`, `first<number>`, etc. This is where generics get their name. Generic means "relating to a class or group of things; not specific." Our `first` function works with any array contents. It's not specific; it's generic.
Generics allow us to write one function that can be reused with many types. Dynamic languages like JavaScript can also do this. However, TypeScript generics let us do it while maintaining our guarantee that the types all match.
Generics also work when the result is assigned to an inferred variable.
```ts
function first<T>(elements: Array<T>): T {
return elements[0];
}
let n = first<number>([1, 2]);
let n2 = n;
n2;
```
In the foregoing example, `n` and `n2` are both inferred to have type `number`.
#### More info
[Some website](https://test.com)
___
**Tags**: