gpt4 book ai didi

typescript :如何设置方法返回值=>子类

转载 作者:搜寻专家 更新时间:2023-10-30 20:56:14 25 4
gpt4 key购买 nike

我有一个包含两个子类的父类:

abstract class Point {
public readonly x: number;
public readonly y: number;

constructor(x: number, y: number) {
this.x = x;
this.y = y;
}

diff(point: Point): Point {
return this.update(this.x - point.x, this.y - point.y);
}
// many methods like diff(); and then...

protected abstract update(x: number, y: number): Point;
}



class ImmutablePoint extends Point {
protected update(x: number, y: number): Point {
return new ImmutablePoint(x, y);
}
}



class MutablePoint extends Point {
public x: number;
public y: number;

protected update(x: number, y: number): Point {
this.x = x;
this.y = y;
return this;
}
}


const pointA: ImmutablePoint = new ImmutablePoint(10, 10)
const pointB: ImmutablePoint = new ImmutablePoint(6, 2);

但是 diff() 方法返回一个 Point,而不是 ImmutablePoint

// Error: type 'Point' is not assignable to parameter of type 'ImmutablePoint'.
const result: ImmutablePoint = pointA.diff(pointB);

我正在寻找一种无需编写新实现即可在子类上重新定义方法签名的方法,这可能吗?

我还尝试让 diff() 返回值 this 但它不起作用,因为 ImmutablePoint 不返回 this 而是返回一个新的不可变点

Playground Link

最佳答案

您可以将 this 作为返回类型,并且可以使用 this.constructor 访问当前对象的构造函数。这使您可以更轻松地使用子类化的不可变对象(immutable对象)。

abstract class Point {
public readonly x: number;
public readonly y: number;

constructor(x: number, y: number) {
this.x = x;
this.y = y;
}

diff(point: Point): this {
return this.update(this.x - point.x, this.y - point.y);
}
// many methods like diff(); and then...

protected abstract update(x: number, y: number): this;
}



class ImmutablePoint extends Point {
protected update(x: number, y: number): this {
return new (<any>this.constructor)(x, y);
}
}



class MutablePoint extends Point {
public x: number;
public y: number;

protected update(x: number, y: number): this {
this.x = x;
this.y = y;
return this;
}
}


const pointA: ImmutablePoint = new ImmutablePoint(10, 10)
const pointB: ImmutablePoint = new ImmutablePoint(6, 2);
const result: ImmutablePoint = pointA.diff(pointB);

关于 typescript :如何设置方法返回值=>子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42705406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com