使用绑定时强制输入

时间:2019-03-20 10:52:28

标签: typescript function-binding

我正在尝试创建一个函数的绑定版本,该函数的参数已预先设置,但是我无法在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();

目前看来bind的TypeScript签名是

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

有什么办法可以使类型检查与bind一起正常工作?

我曾尝试创建一个index.d.ts,但是我对如何将函数参数声明为泛型感到困惑。

2 个答案:

答案 0 :(得分:2)

3.2和更高版本中有编译器选项,称为here,称为strictBindCallApply。您还可以只启用strict,这也会启用strictBindCallApply

激活此选项,您将在此行上收到错误消息:

const bound = doSomethingWithValue.bind(null, 'a');

答案 1 :(得分:-2)

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

似乎MS也不知道如何进行绑定,调用和应用强类型