简体   繁体   English

打字稿:为实现和接口或扩展DTO的对象添加原型方法

[英]Typescript: add prototype method for a object which implements and interface or extend DTO

I need to be able to implement either static method against specific interface or extend a DTO which is implementing specific interface. 我需要能够针对特定接口实现静态方法,或者扩展正在实现特定接口的DTO。

Let me try to explain a bit with code: 让我尝试用代码来解释一下:

interface Car {
      dateOfProduction: Date

      age: (car: Car) => number
    }

I am receiving from an API: 我从API收到:

{ dateOfProduction: Date }

Loading it like this: 像这样加载它:

let car: Car = <Car> receivedDto;

I need to call something like 我需要打个电话

Car.age(car)

or if it's possible with prototyping? 还是可以通过原型制作?

Thank you! 谢谢!

You probably want to create a model for your interface to implement your age() function. 您可能想为接口创建一个model以实现age()函数。 You can't put logic in an interface. 您不能在接口中放入逻辑。 It's more of a blueprint. 这更像是一个蓝图。

So let's say you have an interface ICar which has the dateOfProduction property and a function called age which returns a string (i guess). 假设您有一个接口ICar ,它具有dateOfProduction属性和一个名为age的函数,该函数返回一个string (我猜)。

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

Then you want to create a class which implements this interface and the logic for your age function. 然后,您想创建一个实现该interfaceage函数逻辑的class For simplicity i don't put in the actual logic to calculate the 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);
    }

}

Then you probably have a service which fetches the data from your backend. 然后,您可能有一个从后端获取数据的服务。 There you want to create the objects for further use in your app. 您要在此处创建对象以在应用程序中进一步使用。

Something like: 就像是:

@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;
        }
    }

} 

Hope this is what you were looking for. 希望这就是您想要的。

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

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