簡體   English   中英

TypeScript 在這種情況下如何聯合類型

[英]How TypeScript union types on that occasion

您好,我正在一個名為 Point 的 class 內創建一個 function ,它將 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 是否可以創建兩個函數,而不是只創建一個函數?

我認為沒有正確的方法。 但是存在一個小技巧:

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM