Hello I'm creating a function inside a class called Point that sum the value of X and Y with Point or X and Y parameters.
Example:
public Offset(dx: number, dy: number) {
this.X += dx;
this.Y += dy;
}
public OffsetPoint(p: Point) {
this.X += p.X;
this.Y += p.Y;
}
Instead of creating two functions, creating only one, is it possible with typescript?
I think there is no right way. But a small hack exists:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.