代码之家  ›  专栏  ›  技术社区  ›  BeetleJuice

为什么typescript抱怨数组长度?

  •  2
  • BeetleJuice  · 技术社区  · 8 年前

    我有一个接受2到4个参数的方法:

    myMethod(a: string, b: string, c?: any, d?: number);
    

    在单元测试中,我尝试通过以下方式将参数传递给方法:

    const args: [string, string, any, number] = ['a', 'b', 'c', 0];
    myMethod(...args);
    

    即使我宣布 args 若要设置长度,typescript编译器将显示以下错误:

    TS2556:应为2-4个参数,但得到0个或更多。

    为什么显示此错误?我能做些什么保持最后一行(函数调用)不变吗?

    1 回复  |  直到 8 年前
        1
  •  5
  •   jcalz    8 年前

    这是一个 known issue ,为什么会发生这种情况的简短答案是,typescript中的rest/spread支持最初是为数组而不是元组设计的。

    你可以等 tuples in rest/spread positions 在typescript中受支持;应该从 TypeScript 3.0 很快就会出来的。

    在那之前,你唯一的选择是变通办法。您可以放弃扩展语法并逐个传递参数:

    myMethod(args[0], args[1], args[2], args[3]);  // type safe but not generalizable
    

    或者断言您的方法接受 ...args: any[] 如所示:

    (myMethod as (...args:any[])=>void)(...args);  // no error, not type safe
    

    或者忽略错误,

    // @ts-ignore
    myMethod(...args); // no error, not type safe
    

    编辑:或使用 not-currently-well-typed apply() 方法(与前两个解决方法不同,该方法更改发出的js):

    myMethod.apply(this, args); // no error, not type safe
    

    这些都不是很好,所以如果等待特性实现是一个选项,那么您可能希望这样做。祝你好运!