1

我正在尝试创建一个函数的绑定版本,该函数的参数已预先设置,但是我无法对该bind方法进行任何类型的类型检查。

这是我的代码:

interface I {
  a: string;
  b: string;
}

function doSomethingWithValue(value: I) {
  // Do something
}

const ivalue: I = { a: 'a', b: 'b' };

// No error as expected.
doSomethingWithValue(ivalue);

//"Argument of type '"a"' is not assignable to parameter of type 'I'" as expected.
doSomethingWithValue('a');

// No error. Not what I expected
const bound = doSomethingWithValue.bind(null, 'a');

// Will fail
bound();

目前的 TypeScript 签名似乎bind

bind(this: Function, thisArg: any, ...argArray: any[]): any;

有什么方法可以让类型检查正常工作bind吗?

我试过创建一个,index.d.ts但我坚持如何将函数参数声明为泛型。

4

2 回答 2

4

3.2和更新的编译器选项,称为这里strictBindCallApply记录。您也可以仅启用也启用strictstrictBindCallApply

启用此选项后,您将在此行收到错误:

const bound = doSomethingWithValue.bind(null, 'a');
于 2019-03-20T11:08:29.127 回答
-2

您可以查看https://github.com/Microsoft/TypeScript/issues/212

似乎连 MS 都不知道如何绑定、调用和应用强类型

于 2019-03-20T11:08:41.963 回答