# Generics

{% tabs %}
{% tab title="📘 手冊" %}
* TypeScript ⟩ [Generic Object Types](https://www.typescriptlang.org/docs/handbook/2/objects.html#generic-object-types)
{% endtab %}

{% tab title="📗 參考" %}
* Swift ⟩ [Generics](https://docs.swift.org/swift-book/LanguageGuide/Generics.html)
{% endtab %}

{% tab title="👥 相關" %}
* [⭐️ Cheat sheet](../cheatsheet)
{% endtab %}
{% endtabs %}

## Cheatsheet

```typescript
/* ------- ⭐️ Generic type alias -------- */

// ⭐️ generic types
type Optional<T> = T | null;
type OneOrMany<T> = T | T[];
type OptioanlOneOrMany<T> = Optional<OneOrMany<T>>;  // T | T[] | null

// ⭐️ concrete type
type OptionalOneOrManyStrings = OptioanlOneOrMany<string>;
// string | string[] | null

type Box<T> = { contents: T; };


/* ------- ⭐️ Generic interface -------- */

interface Box<T> {        // `T`: type parameter
  contents: T;
}

let box: Box<string>;     // `string`: type argument


/* ------- ⭐️ Generic functions -------- */

function setContents<T>(box: Box<T>, contents: T) {
  box.contents = contents;
}
```

## Topics

* [Generic Functions](generics/functions)
* [Array\<T>](generics/array)

{% hint style="info" %}
types like **Map\<K, V>**, **Set\<T>**, and **Promise\<T>** are also **generic**.
{% endhint %}
