[英]Typescript: add prototype method for a object which implements and interface or extend DTO
我需要能够针对特定接口实现静态方法,或者扩展正在实现特定接口的DTO。
让我尝试用代码来解释一下:
interface Car {
dateOfProduction: Date
age: (car: Car) => number
}
我从API收到:
{ dateOfProduction: Date }
像这样加载它:
let car: Car = <Car> receivedDto;
我需要打个电话
Car.age(car)
还是可以通过原型制作?
谢谢!
您可能想为接口创建一个model
以实现age()函数。 您不能在接口中放入逻辑。 这更像是一个蓝图。
假设您有一个接口ICar
,它具有dateOfProduction
属性和一个名为age
的函数,该函数返回一个string
(我猜)。
export interface ICar {
dateOfProduction: Date;
age(): string;
}
然后,您想创建一个实现该interface
和age
函数逻辑的class
。 为了简单起见,我不使用实际的逻辑来计算年龄。 你可以在这里看看。
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;
}
}
}
希望这就是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.