typescript - 当您不想使用 rest 运算符时,正确使用函数“arguments”内置关键字
问题描述
使用此函数声明:
someFunc(): void {
if(__DEV__) {
this.someOtherFunc.apply(this, arguments);
}
}
当我用参数调用它时,它会失败,如下所示:
- TS2554:预期 0 个参数,但得到 2 个。
正常的方法是使用rest
运算符并忘记arguments
. 我不想那样做,因为我正在使用编译变量__DEV__
,并且我希望在构建时将方法剥离__DEV__
为假。使用 rest 运算符,typescript 在针对 ES5 时在函数中添加一些额外的代码。
有没有办法在打字稿中做到这一点,而不必在@ts-ignore
任何地方使用该方法?
解决方案
您可以通过在别处定义方法的类型来做到这一点:
interface YourObject {
someFunc(...args: any[]): void; // <==== The type of the method goes here
// ...
}
const obj: YourObject = {
// This is the implementation of the method
someFunc(): void {
// Sadly, the type of `arguments` is not compatible with the array
// apply expects, so we have to assert it
this.someOtherFunc.apply(this, arguments as unknown as any[]);
},
// ...
}
obj.someFunc(1, 2); // <==== Works
我在any[]
那里使用过,但当然要使用相关类型。
以 ES5 为目标,输出为:
"use strict";
var obj = {
// This is the implementation of the method
someFunc: function () {
// Sadly, the type of `arguments` is not compatible with the array
// apply expects, so we have to assert it
this.someOtherFunc.apply(this, arguments);
},
// ...
};
obj.someFunc(1, 2); // Works
推荐阅读
- node.js - 云功能 - 获取文档参考文档
- python - Pymodbus:响应中错误的字节数
- pandas - 如何合并来自两个不同 DataFrame 的相同列
- c - 如何将未知类型的指针传递给函数?
- c - 排序最大和最小的字符串
- hive - 尝试使用 nifi 将数据插入配置单元时出错
- visual-studio-code - 贡献有条件激活的 vscode 配置
- vue.js - 尝试使用 highcharts-vue 包装器设置 xAxis 极值
- reactjs - React + Styled Components:每次渲染 setState 都会重置所有组件
- swift - 如何快速刷新所有视图控制器