首页 > 解决方案 > TypeScript 中函数类型中的参数数量错误

问题描述

这是我的代码:

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

正如你在第 XI 行看到的,只传递一个参数,但在 ComparatorFunc 类型中需要两个参数。但是,TypeScript 在这一行没有显示错误。如何解决?

标签: javascripttypescript

解决方案


这不是错误。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.

推荐阅读