简体   繁体   中英

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. However, TypeScript doesn't show error at this line. 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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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