One of the challenges I'm facing is dealing with a time interval encapsulation interface in TypeScript:
export interface TimeBased {
start_time: Date;
end_time: Date;
duration_in_hours: number;
}
To implement this interface, I've created a class called ShiftingTaskDetails:
class ShiftingTaskDetails implements TypeBased, TimeBased {
type: ShiftingTaskType;
start_time: Date;
end_time: Date;
duration_in_hours: number;
constructor(type: ShiftingTaskType, start_time: Date, end_time: Date, duration_in_hours: number) {
this.type = type;
this.start_time = start_time;
this.end_time = end_time;
this.duration_in_hours = Math.abs(end_time.getTime() - start_time.getTime()) / 36e5;
}
}
The issue arises when I have to redundantly calculate duration_in_hours
every time I implement the interface. Is there a way to include derived fields, like duration_in_hours
, directly in the interface definition?
I am puzzled about the best practice within the TS community for handling such scenarios. The abstract pattern that typically transforms an interface into a class doesn't seem applicable here. This becomes particularly challenging as I work with multiple interfaces, each requiring its own set of derived fields.
export interface CountBased {
count: number
}
export interface CountAndPricingBased extends CountBased {
unit_price: number;
count: number;
total_price: number; // total_price should just be unit_price * count
}
Extending two interfaces with specific derived fields poses a dilemma, especially since extending two abstract classes simultaneously isn't feasible.