繁体   English   中英

TypeScript-将返回类型定义为输入类型

[英]TypeScript - Define return type as input type

因此,为简化起见,假设我有如下方法

sum(o: Point | Vector): Point | Vector {
  if (o instanceof Point) {
    return new Point(o.x + this.x, o.y + this.y, o.z + this.z)
  }
  if (o instanceof Vector) {
    return new Vector(o.x + this.x, o.y + this.y, o.z + this.z)
  }
}

正如您所看到的,实际的逻辑是完全相同的,这使得不得不复制它有点愚蠢。 调用方法并将其传递(例如, Point对象)时,返回类型未正确得出。 我必须对Point进行显式转换。

我可以使用通用类型并将参数声明为T但是它当然不会识别xyz变量。

我的问题有点像这个问题,但区别在于我的类型不是数组,而且这个问题没有答案。

可以使用TypeScript更好地解决此问题吗?

您可以显式地传递具有通用约束的构造函数。

function sum<T extends Point | Vector>(c: new (a: number, b: number,c: number) => T, o: T): (T) {  
  return new c(o.x + this.x, o.y +  this.y, o.z + this.z); 
}

let t = x.sum(Point, new Point(1, 2, 3));

我认为您应该使用具有限制的通用类型,例如:

export abstract class SumableClass {

    public sum<T extends SumableClass >(o: T): T {
        return o.constructor(o.x + this.x, o.y + this.y, o.z + this.z);
    }

    constructor(public x: number, public y: number, public z: number) {

    }
}

还定义了一个抽象(SumableClass),Point和Vector应该从中继承

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM