这是我的代码:
type ComparatorFunc<T> = (o1: T, o2: T) => number;
export interface Comparable<T> {
compareTo(o: T): number;
test(func: ComparatorFunc<T>);
}
let c: Comparable<number> = null;
c.test((a: number) => { return 0}); //LINE X
正如您在第 X 行看到的,我仅传递一个参数,但在 ComparatorFunc 类型中需要两个参数。但是,TypeScript 在这一行不会显示错误。如何解决?
最佳答案
这不是一个错误。 TypeScript 不要求您在函数声明中声明所有参数,因为它们可能不会在函数体中使用(因此允许您拥有更清晰的代码)。重要的是,执行总是会以所需的参数数量和类型进行。例如:
// This is valid. No parameters used, so they're not declared.
const giveMe: ComparatorFunc<string> = () => 42
// However during the execution, you need to pass those params.
giveMe() // This will result in an error.
giveMe("the", "answer") // This is fine according to the function's type.
关于javascript - TypeScript 中函数类型的参数数量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785366/