typescript - 使用绑定(bind)时强制输入

标签 typescript function-binding

我正在尝试创建一个已预先设置参数的函数的绑定(bind)版本,但是我无法对 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 但我对如何将函数参数声明为泛型感到困惑。

最佳答案

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

激活此选项后,您将在这一行收到错误:

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

关于typescript - 使用绑定(bind)时强制输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55259033/

相关文章:

Angular-4 d3 v4 问题 : Property 'x' does not exist on type 'HierarchyNode'

javascript - TypeError : this. 名称不是函数

javascript - 解释 bindbind() 函数

Javascript:为什么我可以在不提及原型(prototype)的情况下访问 Function.prototype.call?

javascript - Angular 4 : Call angular function from a global listner

html - 如何在点击时更改按钮标签?

javascript - RxJS 中的 Promise 'finally' 回调等价物

javascript - 为什么这个 MDN 示例在 `undefined` 中使用 `.bind(undefined, 37)` ?

javascript - 如何避免渲染方法中的绑定(bind)或内联箭头函数