首页 > 解决方案 > 当您不想使用 rest 运算符时,正确使用函数“arguments”内置关键字

问题描述

使用此函数声明:

    someFunc(): void {
      if(__DEV__) {
        this.someOtherFunc.apply(this, arguments);
      }
    }

当我用参数调用它时,它会失败,如下所示:

正常的方法是使用rest运算符并忘记arguments. 我不想那样做,因为我正在使用编译变量__DEV__,并且我希望在构建时将方法剥离__DEV__为假。使用 rest 运算符,typescript 在针对 ES5 时在函数中添加一些额外的代码。

有没有办法在打字稿中做到这一点,而不必在@ts-ignore任何地方使用该方法?

标签: typescript

解决方案


您可以通过在别处定义方法的类型来做到这一点:

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

推荐阅读