Property of a general object

I am working with an Interface

export interface ChartDataResponseI {
  consumption: string
  generation: string
  measure_name: string
  point_delivery_number: string
  self_coverage: string
  time: string
}

My goal is to create a generic object property for point_delivery_number, if possible

The updated interface should be structured like this:

export interface ChartDataResponseI<T> {
  consumption: string
  generation: string
  measure_name: string
  [T]: string
  self_coverage: string
  time: string
}

This way, I can specify the key like in these examples:

ChartDataResponse<"point_delivery_number">

or

ChartDataResponse<"community_number">

Answer №1

You have the option to implement a basic intersection.

interface ChartDataResponseI {
  consumption: string
  generation: string
  measure_name: string
  self_coverage: string
  time: string  
}

type ChartDataWithProp<T> = ChartDataResponseI & T;

const chartData: ChartDataWithProp<{point_delivery_number: number, round: string}> = {
  consumption: 'string',
  generation: 'string',
  measure_name: 'string',
  self_coverage: 'string',
  time: 'string',  
  point_delivery_number: 2,
  round: 'yes'
};

TSPlayground

Answer №2

Is it necessary to make it generic? If the only difference lies in those two keys, you might consider implementing something like this:

interface ChartDataResponse {
  consumption: string
  generation: string
  measure_name: string
  self_coverage: string
  time: string
}

export interface ChartDataResponsePointDelivery extends ChartDataResponse {
    point_delivery_number: number
}

export interface ChartDataResponseCommunity extends ChartDataResponse {
    community_number: number
}

With this approach, you have a foundational ChartDataResponse interface that is customized for the specific cases of ChartDataResponsePointDelivery and ChartDataResponseCommunity. This design allows for easy extension if necessary, as both new interfaces inherit from ChartDataResponse while adding their unique keys.

It's worth noting that the base interface is not exposed externally, preventing accidental use without the additional keys. When resorting to accepting "any object", it may indicate an underlying issue with the approach taken. TypeScript aims to provide clarity on the objects being dealt with and their respective keys.

Answer №3

utilize the concept of inheritance

interface ChartDataResponseI {
  consumption: string
  generation: string
  measure_name: string
  //point_delivery_number: string <- if it's not a default value, remove it
  self_coverage: string
  time: string
}

interface Subclass extends ChartDataResponseI {
  point_delivery_number: string
  //or
  anything: string
}

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

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

Capture the height values from various divs and store them in an array, then utilize these values to adjust the size of other

My goal is to achieve the following: (1) Collect heights from multiple divs and store them in an array. (2) Apply these heights to other elements. The first element should receive the first value, the second element should receive the second value of the ...

The flow of Ajax execution halts once the initial calculation is completed

I have been developing an AJAX code that calculates fees. The code works well initially, but it stops functioning when I try to perform a second operation. <script> var weight = document.getElementById("weight").value; var ship_type = document.g ...

Sending form information through AjaxPassing information from a form using

Currently, I am working on a project where one page opens a thickbox of another page that contains a form. Once the form is submitted and data is written to the database, I need the parent page of the thickbox to update specific rows of the form that have ...

When a React Native TextInput is focused, it restricts the ability to press other child components

Issue with Nested TextInput component affecting onPress function of other components. Press only works when the TextInput is not in focus. React Native Version : 0.66.3 Here's the code snippet: export const Component = (props): JSX.Element { const ...

Is it possible to incorporate Vector4's into the geometry of three.js?

Exploring the functionalities of the three.js library has been a fascinating journey for me. As I delve into the intricacies, I've come to understand that the coordinates stored in a mesh's geometry are tuples consisting of (x,y,z). However, bene ...

Where should image manipulation be done - on the server or the client side?

Currently, I am working on a Django-based web application that involves online image manipulation. The goal is to give users the ability to upload their images, apply various manipulations like cropping, filters, and re-ordering, and then send the modified ...

How do I go about extracting and presenting the JSON data from the ESPN API?

In my current project, I am trying to utilize the jQuery library to work with API JSON data. Even though I am experienced in parsing JSON in PHP, I want to explore doing it with jQuery this time around. The goal is to extract information about each of the ...

Looking to deactivate the entire keyboard with JavaScript? Make sure that the start key is not disabled, not even Ctrl

Despite my efforts to disable the entire keyboard using JavaScript, I have encountered some limitations. The Windows Start key and Enter key are not being disabled by my script. <script type='text/javascript'> document.onkeydown = functi ...

How can jQuery distinguish between implicit and explicit CSS height values?

When working with jQuery, I have noticed that both $('#foo').height() and $('#foo').css('height') will return a value regardless of whether a height property is explicitly set using CSS. Is there a way to determine if an eleme ...

Monitor elements in real-time as they are inserted into the DOM using a Chrome Extension

In the process of developing a Chrome extension, I am tackling the task of removing or hiding specific elements based on their id/class. While accomplishing this after the DOM is loaded poses no issue, it does result in a noticeable "blink" on the page dur ...

What is the process to set a Woocommerce checkout field as optional when a checkbox is marked?

I need assistance with customizing the checkout page on Wordpress Woocommerce. Specifically, I want to make the field 'billing_name' not required if the checkbox 'buy_on_company' is checked. Currently, I have successfully hidden ' ...

Start Pane for Hammer.js Carousel

Greetings, I am currently working on a project at my university and I am interested in incorporating "Hammer.js". I have successfully downloaded and implemented the Carousel Example, which is working flawlessly for me. However, I am looking to begin at t ...

What is the process for streaming an mp3 file using express?

I have been utilizing the gTTS module to convert text into a .mp3 file and temporarily save it. However, I am encountering an issue when attempting to stream the file, as the arraybuffer in the response object returned by the endpoint appears to be empty. ...

Tips for showcasing the button label on a different page upon clicking the button

I need help with a functionality where the name of a button clicked on one page is displayed on another page. Here's an example: <a href="#" class="btn btn-danger btn-lg btn-block"> <?php echo $sql->name; ?></a> Currently, echo ...

Ways to fetch a JSON object using JavaScript

Currently, I am in the process of creating an HTML5 mobile application and utilizing jQuery to fetch a JSON file from this URL: . Here is the code snippet I used: var url='http://cin.ufpe.br/~rvcam/favours.json'; $.getJSON(url, function(data, s ...

Using JavaScript to auto-scroll a textarea to a certain position

Is there a way to change the cursor position in a textarea using JavaScript and automatically scroll the textarea so that the cursor is visible? I am currently using elem.selectionStart and elem.selectionEnd to move the cursor, but when it goes out of view ...

Inspecting every element within an array and indicating a negative outcome if any item is not a string

I'm currently working on a function called 'every' that takes in an array and a callback function as arguments. The purpose of the callback function is to determine if all elements in the array meet a certain condition. In my case, I want th ...

Conceal a div element using a button through JavaScript

I've been scouring various online resources for solutions, including Stack Overflow and W3Schools, but I haven't had any luck so far. Here's a simplified version of my current code: <script language="javascript"> function remove() ...