Javascript Typescript:为实现和接口或扩展DTO的对象添加原型方法
我需要能够针对特定接口实现静态方法,或者扩展正在实现特定接口的DTO 让我试着用代码解释一下:Javascript Typescript:为实现和接口或扩展DTO的对象添加原型方法,javascript,typescript2.0,Javascript,Typescript2.0,我需要能够针对特定接口实现静态方法,或者扩展正在实现特定接口的DTO 让我试着用代码解释一下: interface Car { dateOfProduction: Date age: (car: Car) => number } 我从API收到: { dateOfProduction: Date } 像这样加载它: let car: Car = <Car> receivedDto; 或者如果原型设计是可能的话 谢谢大家! 您可能希望为接口
interface Car {
dateOfProduction: Date
age: (car: Car) => number
}
我从API收到:
{ dateOfProduction: Date }
像这样加载它:
let car: Car = <Car> receivedDto;
或者如果原型设计是可能的话
谢谢大家! 您可能希望为接口创建一个
模型
,以实现age()函数。
不能将逻辑放入接口中。这更像是一个蓝图
假设您有一个接口ICar
,它有dateOfProduction
属性和一个名为age
的函数,该函数返回一个字符串(我猜)
然后,您需要创建一个类
,该类实现此接口
以及年龄
函数的逻辑。为了简单起见,我没有用实际的逻辑来计算年龄
然后您可能有一个从后端获取数据的服务。您希望在此处创建对象,以便在应用程序中进一步使用
比如:
@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;
}
}
}
@Injectable()
出口级汽车服务{
构造函数(私有_backendService:backendService){
}
getMyCar():可观察{
//我们在这里调用后端服务或直接使用'http'。。。
此.u backendService.get('/api/mycar/')。订阅(响应:ICar){
//所以我们的反应是我们的汽车接口,
//我们可以在构造函数中使用它,然后创建一个实例
//然后用它做点什么,比如得到年龄
let myCar:Car=新车(响应);
console.log(myCar.age());
返回车;
}
}
}
希望这就是你想要的。我真的不明白这个问题。你不想使用一个“car”类来实现你的接口吗?DTO来自一个API,只有生产日期。我想将年龄作为自动计算属性,或者在界面上附加一个helper方法,以便您进行响应。问题在于ICar是否是具有嵌套属性的大型接口。维护变得单调乏味。在typescript中进行深度克隆有“最佳实践”方法吗?在这种情况下,深度克隆是什么意思?或者你是说反思?如果是这样的话,你应该在这里查找一些关于这个主题的其他问题。但是,对于这种方法的可维护性问题,我没有一个通用的答案。
export interface ICar {
dateOfProduction: Date;
age(): string;
}
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;
}
}
}