typescript - 在那种情况下 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;
}
不是创建两个函数,只创建一个,打字稿是否可行?
解决方案
我认为没有正确的方法。但是存在一个小技巧:
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
推荐阅读
- java - 如何在 getClass().getResource() 中给出文件的正确路径
- javascript - 无法让 ChartJS xAxes 显示为分钟和秒
- jenkins - 来自groovy函数的美元符号Shell脚本后的非法字符串正文字符
- javascript - ApiRTC 令牌认证
- javascript - 在不考虑其直接父项的情况下获取开始和结束偏移值的范围
- sql - SQL Server - 选择多个列按 1 列分组
- reactjs - 如何在 GraphQL 中使用正则表达式检查数组
- php - Prestashop 1.6 将 tinymce 字段添加到管理员首选项
- c# - 如何在c#ViewModel中定义包含空格的sql输出标题?
- php - 如何在字符串 PHP 中仅去除多个空格