Interface-derived properties

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.

Answer №1

To avoid using an Interface in this situation, opt for an abstract class like TimeBased to incorporate the required logic for field calculation directly within the constructor. Subsequently, any derived classes can invoke this logic by calling super within their own constructors.

Answer №2

If you're looking to incorporate implementation in the parent class instead of just outlining its structure, consider defining it as an abstract class:

Unlike an interface, an abstract class can include implementation details for its members.

Since the duration_in_hours is a calculated value based on other properties, it's best implemented as an accessor. Here's an example:

abstract class AbstractTime {
  start_time: Date;
  end_time: Date;

  get duration_in_hours(): number {
    return Math.abs(this.end_time.getTime() - this.start_time.getTime()) / 36e5;
  }
}

class ShiftingTaskDetails extends AbstractTime implements TypeBased {
  constructor(public type: ShiftingTaskType, public start_time: Date, public end_time: Date) {
    super();
  }
}

Additionally, this code snippet utilizes parameter properties to streamline the constructor.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding key/value pairs to an array of objects in RxJS Observables can be easily

I currently have an Angular app with state management that retrieves data from a database in observables. Here is an example of the interfaces I am working with: interface Service { id: number, name: string, category_id: number, } interface Category ...

Using jQuery to access the ID of a div and create a custom close button

I am trying to implement a close button for my popup DIVs. Each one has a unique ID and I want to hide them by setting the CSS 'display' property to 'none' when closed. However, the following example is not functioning as expected. I a ...

Laravel Mix fails to recognize VueJs integration in Laravel

Having an issue setting up VueJs with laravel 5.7 and mix where it keeps saying VueJs is not detected. I've already executed the npm install command. Below is my welcome view: <!doctype html> <html lang="{{ str_replace('_', '- ...

Angular Object Error: Unhandled Exception

As someone who is new to Angular, I am still trying to grasp how it functions. However, I have encountered an issue early on that is causing the below code to produce an "Uncaught Object" error in the console and disrupt Angular functionality. It seems t ...

Having issues with unchecking checkboxes in ReactJS

I created a task management app and I thought of improving it by displaying all completed tasks when the "Show completed tasks" box is checked. https://i.stack.imgur.com/RkXsw.png The issue I'm facing is that while checking "Show completed tasks ...

The D3 force layout is currently displaying just a single connection

I've been experimenting with a graph that I found in this demo and now I want to modify it to display data from Spotify. I created a sample JSON file and adjusted the script accordingly for the new data format, everything seems to be working fine exc ...

Uploading and saving data to an object in FaunaDB using React hook forms

I am currently facing an issue with uploading/saving data to an object in FaunaDB. Specifically, I am trying to upload a string to a jobProfile object: data: { "jobProfile": { "image": "" "coverImage": " ...

Improve the looping mechanism to efficiently extract key values from an object and store them in an array

I am working with an object that contains various questions, each with a different difficulty level indicated by the "difficulty" property. I have implemented a for loop to sort the questions into categories based on their relative difficulty, such as easy ...

Typescript declaration for a .js file in a diverse project

Hey there! I'm currently in the process of converting my JavaScript React Redux project to TypeScript, and I've decided to kick things off by tackling my redux reducers file. Here's a snapshot of how my project is structured: Project/ .. ...

Tips for adding items to a Form Array in Angular

I am working on a project with dynamic checkboxes that retrieve data from an API. Below is the HTML file: <form [formGroup]="form" (ngSubmit)="submit()"> <label formArrayName="summons" *ngFor="let order of form.controls.summons.controls; let i ...

Unable to integrate a new third-party script into a Next.js application

In my attempt to integrate the following script, I have tried adding it first to _document.js, then to app.js, and finally to a specific page. <Script src="https://anywebsite.ai/chatbot/chatbot.js"></Script> <Script id=" ...

Determining the Right Version of a Framework in npm: A Guide

One common issue I encounter is the uncertainty of which versions of npm, Ionic, and other tools I should have installed. It often goes like this: "Oh, there's a new version of the Ionic CLI out. Let's update." I install CLI v3.9.0. ...

Utilizing Javascript to share images from a public Facebook page to a user's timeline via the Facebook API

Can someone assist me with finding a way to share a photo from a public Facebook page to the user's timeline using JavaScript? Is it possible to achieve this with FB.api or FB.ui? I have successfully shared feeds to the timeline using FB.ui, but am no ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

Troubleshooting: Angular CLI project encountering issues on Internet Explorer

Today, I encountered an issue when attempting to create a new project using the Angular CLI. An exception is thrown on IE11 and the console displays the following error message: SCRIPT5007: Unable to get property 'call' of undefined or null ref ...

What is an example scenario where Async Storage can be tested using Jest-expo?

To better understand the testing of Mock-async-storage for reactjs, I decided to replicate an example. If you have any suggestions on a different approach to testing, please feel free to share. I attempted to mimic a use case illustrated on this stack over ...

What is the best way to synchronize API definitions between the server and client using TypeScript?

My setup involves a server (TypeScript, NestJS) and a client (TypeScript, Angular) that communicate with each other. Right now, I have the API response DTO classes defined in both the server to output data and in the client to decode the responses into a ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

The completion event was not triggered during the AJAX request

I am having an issue with a function that I have created to make an ajax call. Despite using the .done method, it does not seem to be firing as expected. Upon checking my console for errors, I came across the following message: function getIncidentInfo( ...

Is there a way to duplicate and insert a function in node.js if I only have its name?

I'm currently working on a code generation project and I've encountered a problem that I initially thought would be easy to solve. However, it seems to be more complicated than I anticipated. My task involves taking a method name as input, naviga ...