Typescript泛型类型未知参数计数

问题描述

我正在尝试使用具有一个函数的泛型类型,一个参数数组然后将其应用到泛型类型的函数,但是typescript无法正确解释args类型

  const animate = async <P,A>(
    action: (payload: P) => any,algorithm: (...args: A[]) => P[],args: A[]
  ) => {
    if (state.playing) return;
    dispatch(togglePlaying());
    const sequence = algorithm(...args);
    for (let element of sequence) {
      await delay(1);
      dispatch(action(element));
    }
    dispatch(togglePlaying());
  };

这是我尝试使用它时遇到的错误

'(rows:number,cols:number,startCell:Coordinates,endCell:Coordinates)类型的参数=> GridT []'不能分配给'(... args:(number | Coordinates)[ ])=> GridT []'

解决方法

您需要的是Parameters<Type>类型:https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype

从函数类型Type的参数中使用的类型构造元组类型。

然后,您可以这样定义函数:

const animate = async <P,F extends (...args: any[]) => P[]>(
    action: (payload: P) => any,algorithm: F,args: Parameters<F>
) => {
    // blah
}

如错误消息所示,如果将algorithm的类型定义为(...args: A[]) => P[],则实际上是在说每个参数都属于同一类型(在您的情况下为number | Coordinates),因此,当您尝试传递(rows: number,cols: number,startCell: Coordinates,endCell: Coordinates) => GridT[]类型的函数时,该函数不匹配。