【问题标题】:TypeScript function property of object parameter interface ... any number of args对象参数接口的TypeScript函数属性...任意数量的args
【发布时间】:2015-12-29 16:41:54
【问题描述】:

我在 Interface 中有一个函数声明,如下所示:

mixin(desc: MixinDescriptor): any;

MixinDescriptor 的定义如下:

interface MixinDescriptor { [id: string]: () => any; }

但是,如果我像这样使用mixin 函数:

chance.mixin({
  test: function(arg1, arg2) {
  }
}

VSCode 会指出它的定义不正确。它可以工作,因为它的实现是这样工作的,但是它的接口声明必须是错误的。

我尝试将MixinDescriptor 更改为:

interface MixinDescriptor { [id: string]: (args: any[]) => any; }

但这也没有用。

我该如何改变它,以便正确地将函数识别为能够接受任意数量的命名参数?

【问题讨论】:

    标签: javascript typescript visual-studio-code


    【解决方案1】:

    试试这样的

     interface MixinDescriptor { 
         [id: string]: (...args: any[]) => any; 
     }
    

    ...表示该函数可以取rest of parameters。由于其余参数是可选的,因此该接口适用于任何类型的功能

    也可以考虑this example

    【讨论】:

    • 具有讽刺意味的是,在我查看的其他答案中,我认为这是事实上的 ... 指示代码不相关。希望这可以在未来以同样的方式帮助某人。好答案!
    猜你喜欢
    • 2017-09-06
    • 2017-09-17
    • 2023-03-20
    • 2015-12-20
    • 2018-12-29
    • 2021-09-09
    • 2021-09-26
    • 2011-04-04
    • 1970-01-01
    相关资源
    最近更新 更多