Here is an array of vehicles with their details.
export const fetchDataFromApi = () => {
return [
{ vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString },
{ vehicleId: 2, vehicleType: 'plane', seats: 200, maxAltitude: 8000, updatedAt: new Date().toISOString },
{ vehicleId: 3, vehicleType: 'train', seats: 1200, railType: 'whatever', updatedAt: new Date().toISOString },
];
};
I have defined Vehicle, Car, Plane and Train classes. My question is whether they could also be Interfaces.
The API response needs to be handled with a DTO to define the response type and facilitate casting it to the DTO type.
How can I convert the data into a typed DTO? Here are my class definitions, but I need help with the implementation.
class Vehicle {
vehicleId: number;
vehicleType: string;
seats: number;
updatedAt: string;
constructor(vehicleId: number, vehicleType: string, seats: number, updatedAt: string) {
this.vehicleId = vehicleId;
this.vehicleType = vehicleType;
this.seats = seats;
this.updatedAt = updatedAt;
}
}
class Car extends Vehicle {
wheelType: string;
constructor(vehicleId: number, vehicleType: string, seats: number, updatedAt: string, wheelType: string) {
super(vehicleId, vehicleType, seats, updatedAt);
this.wheelType = wheelType;
}
}
class Plane extends Vehicle {
maxAltitude: number;
constructor(vehicleId: number, vehicleType: string, seats: number, updatedAt: string, maxAltitude: number) {
super(vehicleId, vehicleType, seats, updatedAt);
this.maxAltitude = maxAltitude;
}
}
class Train extends Vehicle {
railType: string;
constructor(vehicleId: number, vehicleType: string, seats: number, updatedAt: string, railType: string) {
super(vehicleId, vehicleType, seats, updatedAt);
this.railType = railType;
}
}