代码之家  ›  专栏  ›  技术社区  ›  Pavel_K

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

  •  0
  • Pavel_K  · 技术社区  · 7 年前

    这是我的代码:

    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在这一行没有显示错误。如何修复它?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mateusz Kocz    7 年前

    这不是一个错误。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.
    
    推荐文章