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
正如你在第 XI 行看到的,只传递一个参数,但在 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.
推荐阅读
- angular - 单击时有角度的哑光折叠行
- windows - 如何删除带有尾随空格(或句点)字符的 Windows 文件?
- flutter - Flutter中TabBarView添加多个内容
- sql - 如何在未知列中插入默认值
- ruby-on-rails - 与子域相关的 Rails 路由在 aws 上不起作用
- shell - Sed 在特定行之后插入值
- hyperledger-fabric - 在 hyperledger farbic 中通过 TxID 获取交易详情
- python-3.x - 使用 tkinter 按钮在散点图中填充坐标
- c# - 重新运行更新迁移时实体框架核心出现错误
- flutter - 如何在 Flutter 中临时保存文件?