简体   繁体   English

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

[英]Wrong number of parameters in function type in TypeScript

This is my code: 这是我的代码:

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

As you see at line XI pass only one parameter but in type ComparatorFunc two parameters required. 如您在第XI行看到的,仅传递一个参数,但在ComparatorFunc类型中传递两个参数。 However, TypeScript doesn't show error at this line. 但是,TypeScript在此行不显示错误。 How to fix it? 如何解决?

This is not an error. 这不是错误。 TypeScript doesn't require you to declare all parameters in the function's declaration since they might not be used in the function's body (and hence allows you to have a cleaner code). TypeScript不需要您在函数的声明中声明所有参数,因为它们可能未在函数的主体中使用(因此可以使代码更简洁)。 What's important is that the execution will always happen with the required parameters count and types. 重要的是执行将始终以所需的参数数量和类型进行。 For example: 例如:

// 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM