# Generic Functions

{% tabs %}
{% tab title="📗 參考" %}
* 📘 [Generic Functions](https://www.typescriptlang.org/docs/handbook/2/functions.html#generic-functions)
{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}

## Type Parameters

```typescript
// T: type parameter
function firstElement<T>(arr: T[]): T {
  return arr[0];
}

// of type 'string'
const s = firstElement(["a", "b", "c"]);  // "a"
// of type 'number'
const n = firstElement([1, 2, 3]);        // 1
```

{% hint style="warning" %}
**type parameters** are for _relating the types of **multiple values**_ (parameters or return value). If a type parameter is **only** used **once** in the **function signature**, it’s **not needed** after all.
{% endhint %}

## Type Constraints

```typescript
// HasLength
interface HasLength {
  length: number;
}

// longest(a,b)
//              ╭── ⭐️ constraint ──╮
function longest<T extends HasLength>(a: T, b: T) {
  return (a.length >= b.length) ? a : b;
}
 
// of type 'number[]'
const a1 = longest([1, 2], [1, 2, 3]);    // [1, 2, 3]

// of type 'alice' | 'bob'
const a2 = longest("alice", "bob");       // "alice"
```
