Ways to incorporate type into an object comprised of n element in Typescript

Is there a way to assign types to objects with different keys and values, but where "other" remains constant across all of them? How can this be achieved using TypeScript?

{
  color: "red",
  size: "small",
  other: {
     price: 345
     discount: 10
  }
}

{
  ram: "4 GB",
  brand: "Samsung",
  other: {
     price: 755
     discount: 30
  }

}

Answer №1

That scenario is typically more broad and general.

class Product {
    details: {
       price: number;
       discount: number;
    };
    [key: string]: any;
}

However, if you are able to establish some boundaries and pinpoint specific instances, it would be much more effective to create a parent class with shared properties like details, and then define child classes for the specialized (yet constrained) fields, such as:

class Product {
    details: {
       price: number;
       discount: number;
    };
}

class Clothing extends Product {
     size: string;
     color: string;
}

class Electronics extends Product {
     capacity: string;
     brand: 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

Is there a way to retrieve the attributes of a generic object using an index in TypeScript?

I'm currently working on a function that loops through all the attributes of an object and converts ISO strings to Dates: function findAndConvertDates<T>(objectWithStringDates: T): T { for (let key in Object.keys(objectWithStringDates)) { ...

Tips for integrating Reactjs with Chessboard.js

Recently, I stumbled upon chessboardjs (https://chessboardjs.com/) as a way to hone my React coding skills. However, I hit a roadblock while trying to implement a simple example of displaying the chess board in my application. The documentation instructed ...

Utilizing UI-GRID to showcase JSON information

I am currently in the process of fetching data from the server. [ { id:1, name:demo, request: { id: 1, localCompany: { id: 1 } } }] [{ }, { }] This is how my JSON object appears to be structured. After calling ...

How does one distinguish between the uses of "any" and "any[ ]"?

Exploring the Difference Between any and any[ ] An Illustrative Example (Functioning as Expected) variable1: any; variable2: any[]; this.variable1 = this.variable2; Another Example (Also Functioning as Intended) variable1: any; v ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Using Typescript to specify the parameter type of a function as a generic function

After creating a function called compose, it looks like this: const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x)); It appears to me that both functions f and g fall under the type fGeneric, which is define ...

There was a DOMException in Angular because the transaction is not active when trying to execute 'getAll' on 'IDBObjectStore'

private get ctxMessage() { const messageTransaction = this.db.transaction('messages', 'readwrite'); const messageStore = messageTransaction.objectStore('messages'); return { messageTransaction, messageStore }; } ...

I am attempting to update the URL of an iframe dynamically, but I am encountering an issue: the Error message stating that an Unsafe value is being

Currently, I am attempting to dynamically alter the src of an iframe using Angular 2. Here is what I have tried: HTML <iframe class="controls" width="580" height="780" src="{{controllerSrc}}" frameborder="0" allowfullscreen></iframe> COMPONE ...

Trouble integrating PDF from REST API with Angular 2 application

What specific modifications are necessary in order for an Angular 2 / 4 application to successfully load a PDF file from a RESTful http call into the web browser? It's important to note that the app being referred to extends http to include a JWT in ...

Angular is failing to show any data on the display, despite there being no apparent errors

As a newcomer to Java and Angular, I am currently enrolled in a course on getting started with Angular. I have been attempting to display information in the navigator, but for some reason, nothing is showing up. Despite thoroughly checking my code, I could ...

Troubles arise when trying to compile Typescript and React with esbuild

I set out to create a new package and upload it to npm, starting with a demo package first. I began by using this repository as a foundation: https://github.com/wobsoriano/vite-react-tailwind-starter After that, I made updates to the build script: " ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

Error in Visual Studio 2019 - TypeScript version discrepancy

I am completely puzzled by the mismatch in Typescript versions when using Visual Studio 2019 with my .NET Core 2.2.x project. Every time I make changes to a .ts file, I receive the following warning (found in the error list): Your project is built using ...

Error: TypeScript cannot locate the specified <element> in the VSCode template

After conducting some observations, I've come to realize that the error is specific to the first .tsx file opened in VSCode. Once IntelliSense runs on this initial file, the error appears. Subsequent files work fine without any issues. To troubleshoo ...

Accessing a data property within an Angular2 route, no matter how deeply nested the route may be, by utilizing ActivatedRoute

Several routes have been defined in the following manner: export const AppRoutes: Routes = [ {path: '', component: HomeComponent, data: {titleKey: 'homeTitle'}}, {path: 'signup', component: SignupComponent, data: {titleKe ...

Errors may occur when utilizing TypeScript with the Context Provider API in React

I am in the process of developing a theme changer feature and I want to save the color chosen by the user in the context. However, when I try to pass data to the value prop of the Context.Provider, I encounter an error message TS2739: Type 'Readonly&l ...

Expanding TypeScript Definitions

I've been experimenting with TypeScript and Express. After importing type declarations from Typings, I found the following code: // Imported from typings // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f2 ...

Using debounceTime and distinctUntilChanged in Angular 6 for efficient data handling

I recently came across a tutorial on RxJS that demonstrated the use of debounce and distinctUntilChanged. I'm trying to implement it in Angular 6, but I'm facing some challenges. Here is the code from the tutorial: var observable = Rx.Observabl ...

Exporting constants using abstract classes in TypeScript files

In my Typescript files, I've been exporting constant variables like this: export const VALIDATION = { AMOUNT_MAX_VALUE: 100_000_000, AMOUNT_MIN_VALUE: 0, DESCRIPTION_MAX_LENGTH: 50, }; My constant files only contain this one export without any ...

How can one change the data type specified in an interface in TypeScript?

I am currently diving into TypeScript and looking to integrate it into my React Native application. Imagine having a component structured like this: interface Props { name: string; onChangeText: (args: { name: string; value: string }) => void; s ...