typescript - 使用绑定时强制输入
问题描述
我正在尝试创建一个函数的绑定版本,该函数的参数已预先设置,但是我无法对该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
但我坚持如何将函数参数声明为泛型。
解决方案
有3.2
和更新的编译器选项,称为这里strictBindCallApply
记录。您也可以仅启用也启用strict
strictBindCallApply
启用此选项后,您将在此行收到错误:
const bound = doSomethingWithValue.bind(null, 'a');
推荐阅读
- python - 如何在 python 中将 csv 中的两列组合为我的 ggplot 的 x 轴?
- java - MD5 - 未定义字符串类型的方法
- json - 以编程方式用数据填充 Firestore 文档
- mysql - 需要为现有项目动态更改时区
- angular - input[ngbdatepicker] 指令的用例
- java - 为什么我的控制台输入没有终止。如果我删除代码 countSwaps(a,size) 则控制台输入终止,否则不会
- java - C#接口协方差,指定参数类型
- python - findall 语句中的 " 问题
- c# - 有没有办法使用不存在的成员变量从字典中选择一个元素?
- openedge - SQL Explorer 中 -char 参数的用途是什么?