我正在尝试创建一个已预先设置参数的函数的绑定(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/