Typescript implements strict enforcement of partial interfaces

In my application, I am working with JSON data. Here is a simplified example:

data {
  prop1: "abc",
  prop2:  123,
  COL_A12: "mydata",
  COL_A13: "myotherdata",
}

I am aware that the data will consist of multiple prop1 and prop2 properties. However, COL_A12 and COL_A13 are dynamically generated, so they could have different names (e.g., COL_A67).

I have defined an interface as follows:

interface IData {
  prop1: string;
  prop2: number;
}

Unfortunately, I cannot specify the other property names in the interface due to their dynamic nature. They do follow a pattern, though.

Is there a way to use regular expressions for property names in Typescript?

Answer №1

There is no fixed pattern for setting property names.

interface IData {
    prop1: string;
    prop2: number;
    [name: string]: string | number;
}

For example:

let data = {
    prop1: "abc",
    prop2:  123,
    COL_A12: "mydata",
    COL_A13: "myotherdata",
} as IData;

console.log(data.prop1); // okay
console.log(data.COL_A12); // error
console.log(data["COL_A12"]); // okay

The challenge lies in the fact that indexable properties have type string | number, so:

let a = data["COL_A12"]; // typeof a is 'string | number'
let b = data["COL_A12"] as string; // typeof a is 'string'

Edit

Once you receive the data, you cannot control its contents (if I understand correctly). The interface provided helps to understand the structure of the received data.

To manage how this data is accessed in your application, consider creating a class that takes the data and provides specific getters:

class Data {
    private raw: IData;

    constructor(data: IData) {
        this.raw = data;
    }

    public get prop1(): string {
        return this.raw.prop1;
    }

    public get prop2(): number {
        return this.raw.prop2;
    }

    public col(num: number): string {
        return this.raw[`COL_A${ num }`] as 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

Guide to adding jquery with typings installation

Need assistance: typings install jquery --global typings ERR! message Unable to find "jquery" ("npm") in the registry. Did you want to try searching another source? Also, if you want contribute these typings, please help us: https://github.com/typings/re ...

Ensure that the query value remains constant in Express.js

Issue: The query value is changing unexpectedly. // url: "http://localhost:4000/sr?q=%C3%BCt%C3%BC" export const search = async (req: Request, res: Response) => { try { const query = String(req.query.q) console.log("query: &quo ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Issues with style not loading properly within innerHTML in Angular2

Currently, I am in the process of developing a page using Angular2/4 that includes a left navigation bar. To achieve reusability, I have separated this left menu into its own component and nested it within the main component. The objective is to utilize th ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

Angular - How to fix the issue of Async pipe not updating the View after AfterViewInit emits a new value

I have a straightforward component that contains a BehaviorSubject. Within my template, I utilize the async pipe to display the most recent value from the BehaviorSubject. When the value is emitted during the OnInit lifecycle hook, the view updates correc ...

Typescript error: Undefined reference to 'DhImportKeyParams'

Working on a project, I encountered an issue with a third-party library written in Typescript 3.7. The outdated library depended on the 'lib' that contained an interface called DhImportKeyParams. However, my current project uses Typescript 4.6 wh ...

What factors contribute to the variations in results reported by Eslint on different machines?

We initially utilized tslint in our project but recently made the switch to eslint. When I execute the command "eslint \"packages/**/*.{ts,tsx}\"" on my personal Windows machine, it detects 1 error and 409 warnings. Surprising ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

Is there a way to achieve region collapsing and expanding using #region / #endregion in TypeScript within Visual Studio Community Edition 2019?

For a while now, we've been utilizing "region collapsing" in TypeScript as shown below: //#region GUI handlers ...code related to handling GUI events... //#endregion This method has functioned well in VS2015 CE and VS2017 CE, with a small "-" or "+" ...

Bringing together the functionality of tap to dismiss keyboard, keyboard avoiding view, and a submit button

On my screen, there's a big image along with a text input and a button at the bottom. The screen has three main requirements: When the user taps on the input, both the input and button should be visible above the keyboard The user must be able to ta ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

Navigating an immutable list to make updates to its values

Within this list, I have an unalterable group of objects. My task is to change the value of the 'isReq' property to false for all objects except the one with the id 2. [ { 'id': 1, 'name': 'Ram', 'D ...

Using Typescript: ForOf Iteration with Unknown Value Types

My journey began with a quick peek at this particular inquiry. However, the approach discussed there utilized custom typing. I am currently iterating over object entries using a for-of loop. Here's a snippet of the values I'm dealing with below. ...

I am facing the dilemma of having an identical button appearing in two separate locations. How can I determine which button has been clicked?

I am currently using ng2-smart-table and have implemented a custom filter with the same button in both filters. However, I am unsure of how to determine which button is being clicked. https://i.stack.imgur.com/b1Uca.png Below is the component code for th ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...

What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object. The main table is called sentinel and the secondary table is named sensor https://i.sstatic.net/1BrRq.png https://i.sstatic.net/3lOVD.png It can be observ ...

Transmit data via XMLHttpRequest in smaller portions or through a ReadableStream to minimize memory consumption when handling large datasets

Recently, I've been experimenting with JS's XMLHttpRequest Class for handling file uploads. Initially, I attempted to upload files using the following code: const file = thisFunctionReturnsAFileObject(); const request = new XMLHttpRequest(); req ...

Encountering issues while attempting to transmit several files to backend in React/NestJS resulting in a BAD REQUEST error

My goal is to allow users to upload both their CV and image at the same time as a feature. However, every time I attempt to send both files simultaneously to the backend, I encounter a Bad Request error 400. I have made various attempts to troubleshoot th ...