# Bind is Bad

これは`lib.d.ts`の`bind`の定義です：

```typescript
bind(thisArg: any, ...argArray: any[]): any;
```

見ての通り、**any**を返します!つまり、関数の`bind`を呼び出すと、元の関数のシグネチャの型安全性が完全に失われます。

たとえば、次のようにコンパイルします:

```typescript
function twoParams(a:number,b:number) {
    return a + b;
}
let curryOne = twoParams.bind(null,123);
curryOne(456); // Okay but is not type checked!
curryOne('456'); // Allowed because it wasn't type checked!
```

それを書くためのよりよい方法は、明示的な型アノテーションを持つ単純な[アロー関数](/deep-dive/future-javascript/arrow-functions.md)です。

```typescript
function twoParams(a:number,b:number) {
    return a + b;
}
let curryOne = (x:number)=>twoParams(123,x);
curryOne(456); // Okay and type checked!
curryOne('456'); // Error!
```

しかし、あなたがカリー化された関数を必要とする場合は、[それにはより良いパターンがあります](/deep-dive/main-1/currying.md)。

## クラスメンバ

`bind`の別の一般的な使い方は、クラス関数を渡すときに`this`の正しい値を保証するために`bind`を使うことです。それはやらないでください!

次の例は、`bind`を使うとパラメータの型安全性を失うことを示しています：

```typescript
class Adder {
    constructor(public a: string) { }

    add(b: string): string {
        return this.a + b;
    }
}

function useAdd(add: (x: number) => number) {
    return add(456);
}

let adder = new Adder('mary had a little 🐑');
useAdd(adder.add.bind(adder)); // No compile error!
useAdd((x) => adder.add(x)); // Error: number is not assignable to string
```

もしあなたが他に渡すことを期待しているクラスメンバ関数を持つ場合は、そもそも[アロー関数](/deep-dive/future-javascript/arrow-functions.md)を使います。例えば、上記と同じ`Adder`クラスを以下に示します:

```typescript
class Adder {
    constructor(public a: string) { }

    // This function is now safe to pass around
    add = (b: string): string => {
        return this.a + b;
    }
}
```

もう1つの方法は、バインドする変数の型を手動で指定することです。

```typescript
const add: typeof adder.add = adder.add.bind(adder);
```


---

# Agent Instructions: 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:

```
GET https://typescript-jp.gitbook.io/deep-dive/main-1/bind.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
