> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/appendix/typescript/type/generics/functions.md).

# 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"
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://lochiwei.gitbook.io/web/appendix/typescript/type/generics/functions.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
