gpt4 book ai didi

javascript - typescript : add prototype method for a object which implements and interface or extend DTO

转载 作者:行者123 更新时间:2023-12-01 04:04:50 26 4
gpt4 key购买 nike

我需要能够针对特定接口(interface)实现静态方法或扩展正在实现特定接口(interface)的 DTO。

让我尝试用代码解释一下:

interface Car {
dateOfProduction: Date

age: (car: Car) => number
}

我从 API 接收:

{ dateOfProduction: Date }

像这样加载:

let car: Car = <Car> receivedDto;

我需要调用类似的东西

Car.age(car)

或者是否可以通过原型(prototype)设计实现?

谢谢!

最佳答案

您可能想为您的界面创建一个模型来实现您的age()函数。您不能将逻辑放入界面中。它更像是一个蓝图。

假设您有一个接口(interface) ICar,它具有 dateOfProduction 属性和一个名为 age 的函数,该函数返回一个 string(我猜)。

export interface ICar {
dateOfProduction: Date;
age(): string;
}

然后您要创建一个来实现此接口(interface)以及age函数的逻辑。为了简单起见,我没有输入实际的逻辑来计算年龄。 you can take a look here for that.

export class Car implements ICar {

dateOfProduction: Date;

constructor(data: ICar) {
this.dateOfProduction = data.dateOfProduction;
}

age(): string {
return Utils.getYearsSince(this.dateOfProduction);
}

}

那么您可能有一个从后端获取数据的服务。您希望在此处创建对象以便在您的应用程序中进一步使用。

类似于:

@Injectable()
export class CarService {

constructor(private _backendService: BackendService) {
}

getMyCar(): Observable<Car> {

// we call a backendService or directly use `http` here ...

this._backendService.get('/api/mycar/').subscribe(response: ICar) {

// so our response is in the form of our car interface,
// we can just use it in our constructor then, create an instance
// and do something with it, like get the age

let myCar: Car = new Car(response);

console.log(myCar.age());

return car;
}
}

}

希望这就是您正在寻找的内容。

关于javascript - typescript : add prototype method for a object which implements and interface or extend DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914404/

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