首页 > 解决方案 > 在那种情况下 TypeScript 联合类型如何

问题描述

您好,我正在一个名为 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;
}

不是创建两个函数,只创建一个,打字稿是否可行?

标签: typescriptoverloading

解决方案


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

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 

推荐阅读