【问题标题】:How TypeScript union types on that occasion在那种情况下 TypeScript 联合类型如何
【发布时间】:2021-03-10 23:02:57
【问题描述】:

您好,我正在一个名为 Point 的类中创建一个函数,该函数将 X 和 Y 的值与 Point 或 X 和 Y 参数相加。

例子:

public Offset(dx: number, dy: number) {
    this.X += dx;
    this.Y += dy;
}

public OffsetPoint(p: Point) {
    this.X += p.X;
    this.Y += p.Y;
}

用打字稿可以代替创建两个函数,只创建一个吗?

【问题讨论】:

标签: typescript overloading


【解决方案1】:

我认为没有正确的方法。但是存在一个小技巧:

class Point {
    X: number
    Y: number

    constructor(X: number, Y: number) {
        this.X = X;
        this.Y = Y;
    }

    public Offset(dx : number | Point , dy? : number) {
        if (dy) {
          this.X += dx as number;
          this.Y += dy as number;
        } else {
          let p = dx as Point;
          this.X += p.X;
          this.Y += p.Y;
        }
    }
}

let a = new Point(1, 1);
let b = new Point(2, 2)

console.log('a.x', a.X, 'a.y', a.Y); // "a.x",  1,  "a.y",  1 
a.Offset(b)
console.log('a.x', a.X, 'a.y', a.Y); // "a.x",  3,  "a.y",  3 
a.Offset(10, 20)
console.log('a.x', a.X, 'a.y', a.Y); // "a.x",  13,  "a.y",  23 

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 2020-09-03
    • 2022-11-19
    • 2020-02-27
    • 2020-09-30
    • 2019-01-27
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多