简体   繁体   中英

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.

Let me try to explain a bit with code:

interface Car {
      dateOfProduction: Date

      age: (car: Car) => number
    }

I am receiving from an 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. 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).

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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