Dynamic Type in Typescript Record

Looking for a way to attach types to record names in a class that returns a Record. The current code snippet is as follows:

interface DataInterface {
    bar: number;
    foo: string;
    fooBar: boolean;
}

export class MyClass {
  public bar: number;
  public foo: string;
  public fooBar: boolean;

  constructor(data: Record<string, DataInterface>) {
    this.bar = data.bar; // ERROR: Type 'DataInterface' is not assignable to type 'number'.
    this.foo = data.foo; // ERROR: Type 'DataInterface' is not assignable to type 'string'.
    this.fooBar = data.fooBar; // ERROR: Type 'DataInterface' is not assignable to type 'boolean'.
  }
}

How should I approach this issue given the possibility of numerous items in DataInterface?

Answer №1

You have the option to utilize the DataInterface directly

  constructor(data: DataInterface) {
    this.bar = data.bar;
    this.foo = data.foo;
    this.fooBar = data.fooBar;
  }

It is worth noting that DataInterface acts as an Object/Record by default

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

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Implement a function for templateURL in AngularJS using Typescript programming language

Here is my current setup: export class MyComponent implements ng.IComponentOptions { public static componentName: string = "myViewer"; public bindings: any; public controller: any; public controllerAs: any; public templateUrl: string; ...

Do not allow nested objects to be returned

I am facing an issue with typeorm, where I have a queryBuilder set up like this: const projects = await this.conn.getRepository(UserProjectRelations).createQueryBuilder("userProject") .innerJoin("userProject.userId", ...

Issue with retrieving all phone numbers from a contact in Ionic

Hope you're doing well! I'm encountering an issue with Ionic Contacts. Currently, I'm able to retrieve all the contacts using my code but I need help extracting all the phone numbers associated with each contact. For example, if John has 3 ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

What is the best way to transition this endpoint from JavaScript to TypeScript?

I'm in the process of building a chat application with the t3 stack. I've successfully created a socket endpoint using JavaScript, but now I'm facing some challenges as I try to convert it to TypeScript. import { Server } from "Socket.I ...

The 'component' property is not found in the 'IntrinsicAttributes' type in this context

I am facing an issue with a component that is not compiling properly: export default function MobileNav({routes, currentRouteIndex, handlePressedRoutedIndex}: MobileNavProp) { ... return ( <React.Fragment> ... ...

An error is encountered when attempting to retrieve the list using axios

For this project, I am required to fetch a list from the following resource: http://jsonplaceholder.typicode.com/photos The controller setup is as follows: @JsonController('/photo') @Service() export class PhotoController { const ...

An error occurred while attempting to set up Next-auth in the process of developing

In my Next.js app, I have implemented next-auth for authentication. During local development, everything works fine with 'npm install' and 'npm run dev', but when I try to build the project, I encounter this error message: ./node_modul ...

Typescript custom sorting feature

Imagine I have an array products= [{ "Name":'xyz', 'ID': 1 }, { "Name":'abc', 'ID': 5 }, { "Name":'def', 'ID': 3 } ] sortOrder=[3,1,5] If I run the following code: sortOrder.forEach((item) =&g ...

Creating a Loading Sign with a Button Component in React

Request Description: In my form, I have a button that triggers a submission to the backend. While the request is processing, I want the button to display a loading indicator instead of the usual text. Once the request is complete, I need the form to disap ...

Adjusting the value of a mat-option depending on a condition in *ngIf

When working with my mat-option, I have two different sets of values to choose from: tempTime: TempOptions[] = [ { value: 100, viewValue: '100 points' }, { value: 200, viewValue: '200 points' } ]; tempTimesHighNumber: TempOpt ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

Implement a personalized Laravel Dusk selector with the attribute data-dusk

In the world of Laravel Dusk, the default selector hunts for the dusk="something" attribute in your HTML. If you want to dive deeper into this topic, check out this resource. However, when it comes to compatibility with Typescript for React/Vue, ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

What specific type should be used for validations when incorporating express-validator imperative validations?

Having trouble implementing express-validator's imperative validations in TypeScript because the type for validations cannot be found. // reusable function for multiple routes const validate = validations => { return async (req, res, next) => ...

What is the best way to send information to a child component that has been navigated from a parent component

When navigating to a child component from the parent component's HTML template using a button, how can I pass the parent component's data (such as a name) to the child component without displaying it in the URL? ...

Switching from module.exports in Javascript to Typescript format

My Node-express code currently uses module.exports to export functions. As I am converting the code to TypeScript, I need to find out how to replace module.exports in typescript. Can you help me with this? ...

Ignore verification of unused parameters

In my typescript project compilation process, I make use of the noImplicitAny option to ensure that I specify the types for variables and arguments. However, there are instances where I have unused arguments. For instance: jQuery.ajaxTransport("+*", func ...

Exploring the complexities of cyclic dependencies and deserialization in Angular

I have encountered an issue with deserializing JSON objects in my Angular project. After receiving data through httpClient, I realized that I need to deserialize it properly in order to work with it effectively. I came across a valuable resource on Stack O ...