javascript - TypeScript 中函数类型的参数数量错误

标签 javascript 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

正如您在第 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/

相关文章:

javascript - 通过包装和减少执行语句来提高 Javascript 性能

javascript - 使用字符串从父对象访问预定义的子对象

typescript - 如何将 TypeScript Map 与错误处理程序一起使用?

javascript - 无法识别 ES6 - NodeJS 和 WebStorm

javascript - 在express.js中,res.render()不起作用

javascript - 这段代码中的箭头函数在做什么?

javascript - 继续图像的滚动效果吗?

reactjs - 来自 "react"的 ReactFragment 是什么意思?

TypeScript array.map 允许具有 interred 返回类型的附加属性

angular - Firestore 的 getCountFromServer() 出现错误