【问题标题】:Function overloading, problem with arguments函数重载,参数问题
【发布时间】:2020-01-06 21:46:54
【问题描述】:

在这段代码中声明了几个重载函数:

export function rect(a: Point, b: Point): Rect;
export function rect(a: Point, b: number|Point, c?: number): Rect;
export function rect(a: number|Point, b: number|Point, c?: number, d?: number ) {return new Rect(a,b,c,d);}
rect( 1,1,1, 1)   // ts: "Expected 2-3 arguments, but got 4.ts(2554)"

Typescript 在第 4 个参数中抱怨。我想不出这里有什么问题。如果我再添加一个重载和一个 arg:

export function rect(a: Point, b: Point): Rect;
export function rect(a: Point, b: number|Point, c?: number): Rect;
export function rect(a: number|Point, b: number|Point, c?: number, d?: number ): Rect ;
export function rect(a: number|Point, b: number|Point, c?: number, d?: number, e?: number ): Rect {return new Rect(a,b,c,d);}
rect( 1,1,1, 1)

ts 不会抱怨(如果我将第 5 个参数添加到对 rect 的调用中,它会给出相同的错误)

怎么了?

【问题讨论】:

  • 函数实现必须满足所有重载定义。如果您需要更多参数,请添加另一个重载

标签: typescript overloading


【解决方案1】:

最后一个重载签名是实现签名,对外不可见。如果您想公开该接口,则需要复制它:

export function rect(a: Point, b: Point): Rect;
export function rect(a: Point, b: number | Point, c?: number): Rect;
export function rect(a: number | Point, b: number | Point, c?: number, d?: number): Rect;
export function rect(a: number | Point, b: number | Point, c?: number, d?: number) {
    return new Rect(a, b, c, d);
}

【讨论】:

    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2011-09-23
    相关资源
    最近更新 更多