打字稿通用类型未知参数计数
Typescript generic type unknown arguments count
我正在尝试创建一个具有泛型类型的函数,该函数采用一个函数及其参数数组,然后将它们应用于它,但 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) 类型的参数)[]) => 网格T[]'
你需要的是Parameters<Type>
类型:https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype
Constructs a tuple type from the types used in the parameters of a function type 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[]
的函数时,它不匹配。
我正在尝试创建一个具有泛型类型的函数,该函数采用一个函数及其参数数组,然后将它们应用于它,但 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) 类型的参数)[]) => 网格T[]'
你需要的是Parameters<Type>
类型:https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype
Constructs a tuple type from the types used in the parameters of a function type 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[]
的函数时,它不匹配。