Creating a Typescript interface that allows for the addition of unknown dynamic variables

When creating an interface, I want to have a mix of known variables and dynamic variables.

Consider this initial interface definition:

export interface ApplicationData {
      applicant?: ApplicantData;
      application_unit?: ApplicationUnit;
      interested_people_count?: number | undefined;
}

Now, how can I add the following variables to this interface as well:

interested_person_1: InterestedPerson;
interested_person_3: InterestedPerson;
expenses_1q_2023: Expenses;
expenses_3q_2022: Expenses;

I am uncertain of the exact number of these variables, but I do know that any variable starting with 'interested_person_' should be of type InterestedPerson interface, and any variable starting with 'expenses_' should be of type Expenses interface.

Answer №1

To efficiently categorize data, we must establish two distinct index signatures: one for individuals of interest and the other for expenses. These keys will be defined using template strings.

Here's an example:

type StartsWithInterest = `interest_${string}`

This type will encompass all strings starting with interest_, with the following content being insignificant to the compiler:

const ok: StartsWithInterest = 'interest_correct'
const notOk: StartsWithInterest = 'incorrect' //expected error

By implementing template strings in our index signatures, we can achieve the desired outcome:

type GenericType = {
  [x: `interested_person_${string}`]: InterestedPerson;
  [x: `expenses_${string}`]: Expenses;
};

Experiment with this concept on the TypeScript playground

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

Having performance issues with an HTML5/JavaScript game on Internet Explorer 8

A new game has been developed using html/javascript. Due to confidentiality reasons, the code cannot be fully shared. The game runs smoothly on most browsers except for IE, which poses a challenge. Compatibility with IE8 is essential, despite its limitati ...

Extending a universal design concept to a new theme within the MUI (Material UI) framework

I have implemented MUI's ThemeProvider and set up a Themes.js file. Within this file, I have defined the globalTheme for managing global styles such as typography and border-radius. My intention is to extend the properties of globalTheme to both light ...

Submitting Selected Rows in Angular Material Table: Implementing a Button Click Event

Although a similar question has been addressed on Stack Overflow regarding how to pass selected row values of a table to a button click event in Material design using Angular 6, I did not find the solutions provided there helpful for my specific case. In ...

How to retrieve a response from a vanilla JavaScript AJAX request using the POST method

Here is a PHP function that I created to save data: case "start_question": $user_id = "123"; $p_id = $_POST[""]; $question_id = $_POST["question_Id"]; $answer = $_POST["answer_String"]; $counter = $_POST["counter"]; $points = $_PO ...

Newbie exploring the world of Rails and jQuery

While I am making progress with jQuery and successfully linking js.erb files to controller actions, I have encountered a roadblock. I am unsure of how to make a button, which is not associated with a controller action, trigger specific jQuery commands. My ...

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...

Tips for remaining on the current page after sending a post request using Express

I have a simple question that I haven't been able to find a satisfactory solution for. I've created a post route using express, like this: app.post('/search', function(req, res){ // Code to extract data from req and save it to the d ...

Experiencing issues with regex in JavaScript: all text enclosed within <angular> brackets vanishes

I am trying to analyze a formula and present it on the screen. For instance, I want to be able to input <path>T Q, where <path>T remains unchanged, and Q is a variable. It accepts this input, but when displaying it on the screen, only T Q shows ...

Ways to extract variables from a component and utilize them in App.js

Despite my efforts to search online, I could not find the answer or understand what I needed to. My issue: I need the "inputVal" variable from the "InputField.js" component to be accessible in the "App.js" component (specifically in the fetch request where ...

JavaScript GridView

Is there a way to determine if an ASP.NET GridView contains at least one row by using JavaScript? ...

Issue with loading HTML file correctly in Django

I have been attempting to integrate my Django app with an admin dashboard from a repository on GitHub. After successfully logging in, the app redirects to the dashboard, but only the HTML part loads and none of the fancy features are visible on the dashboa ...

Utilize the Discord API to send a direct message to a specific user by their unique ID

Recently, I've been exploring ways to utilize Discord's API in order to send a private message to a specific user based on their user ID. I understand that there are libraries like Discord.JS and Discord.py that allow for this functionality, how ...

ReactJS: Oops! Looks like there's an issue with the element type - it's invalid. We were expecting a string

I am in the process of setting up a basic server-side rendered React application. Listed below are the steps I have taken: Step 1: Creating a new React app using create-react-app: npx create-react-app my-ssr-app Step 2: Installing necessary dependencies: ...

Using NextJS's API routes to implement Spotify's authorization flow results in a CORS error

I am currently in the process of setting up the login flow within NextJS by referring to the guidelines provided in the Spotify SDK API Tutorial. This involves utilizing NextJS's api routes. To handle this, I've created two handlers: api/login.t ...

How should values be properly stored in a constant using mongoose?

Within my user model, I have included timestamps. I am seeking a way to retrieve the createdAt date and store it in a variable. My initial attempt was: const date = await User.find({ serial: serialId, }).select('-_id createdAt'); The result re ...

Transform JSON data into a JavaScript object

There is a JSON string in a specific format: [{"A":"SomeStringData","B":1}, {"A":"SomeStringData","B":2}, ... ... ...] It should be noted that this JSON string passes through all online parsers successfully and is considered valid. An attempt is being ...

Encountering an error while using *ngIf to filter within a loop in Angular

I'm having trouble using *ngIf to filter out items in a list generated by looping, and it's throwing an error. Can someone please assist me with this issue? abc.component.html <ul> <li *ngFor="let x of students" *ngIf="x.age < ...

New Trainee - Error: document has not been defined

Encountering an Error message while attempting to run Intern tests from the test files directory. The structure of the directory is as follows: test resources rest pickup.js cashManagement.js gitignore intern.js packages.js ...

Having trouble with my Angular application, seems to be stuck at the loading screen. Not sure what's causing it, possibly

Hey there, I'm hoping to create a straightforward app that showcases posts. However, I've encountered an issue when deploying the initial page which is stuck on "Loading...". I believe it's a minor problem and would appreciate your assistan ...

Unable to adjust image opacity using jQuery

I am attempting to change the opacity of an image based on a boolean flag. The image should have reduced opacity when the var pauseDisabled = true, and return to full opacity when pauseDisabled = false. To demonstrate this, I have created a fiddle below. ...