A Model in TypeScript

{
    "title": {
        "de-DE": "German",
        "fr-FR": "French",
        "en-CA": "English"
    },
    "image": "/tile.jpg",
    "url": "/url/to/version"
}

After receiving this JSON data, my model structure is as follows:

export class MyModelStructure {
    title: string;
    image: string;
    url: string;
}

I am looking for the correct approach to include sub-fields for different locales within the 'title' field. Here's what I have in mind:

export class MyModelStructure {
    title: string
    [
       de-DE: string;
       fr-FR: string;
       en-CA: string;
    ];
    image: string;
    url: string;
}

Answer №1

When considering a limited set of languages as specified, you may utilize the provided definition. In situations where you simply plan on converting the JSON object to the model type, it is recommended to use an interface instead of a class:

export interface MyModelDefinition {
    title: {
       'de-DE': string;
       'fr-FR': string;
       'en-CA': string;
    };
    image: string;
    url: string;
}

If the languages are unknown or variable, you can create an object with a string indexer like this:

export interface MyModelDefinition {
    title: {
        [name: string]: string
    };
    image: string;
    url: string;
}

Answer №2

The definition of TS provided may not be suitable for the data at hand. Consider defining title as either an object with key-value pairs where keys are strings and values are strings, or as a simple string. You could use

{ [key: string]: string} | string
to handle either case during runtime.

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

What is the best way to add query parameters to router.push without cluttering the URL?

In my current project, I am using NextJS 13 with TypeScript but not utilizing the app router. I am facing an issue while trying to pass data over router.push to a dynamically routed page in Next.js without compromising the clarity of the URL. router.push({ ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

atom-typescript encounters difficulty locating typings

After setting up a new Angular/Typescript project in Atom with atom-typescript, I encountered an issue. The main angular module file imports all modules and type definition files, but errors are now showing in my .ts files. This is due to atom-typescript n ...

Collaborating on data through module federation

Currently, I am in the process of developing a Vue.js and TypeScript application using Vite. In addition, I am utilizing the vite-module-federation-plugin for sharing code across different applications. My main inquiry revolves around whether it is possibl ...

Disable the default animation

Is there a way to disable the default animation of the Select label in my code snippet below? export default function TicketProfile(props: any) { return ( <Container> <FormControl sx={{ ml: 1, mr: 1, minWidth: 220 }}> <Inp ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...

Simplify an array in Javascript

I have a collection of objects structured in the following way: let list = [ { 'items': [ 'item 1', 'item 2' ] }, { 'items': [ 'item 3' ] } ] My goal is to flatte ...

Why has Jasmine decided not to wait for my promises to finish?

Utilizing the FileSystem API to generate a directory with 2 entries for a test, I am facing an issue where Jasmine does not wait for the promise to resolve before executing the test, resulting in failure. Despite using the async wrapper, the problem persis ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

Component html element in Angular not being updated by service

Within my Angular service, I have a property linked to a text field in a component's HTML. Oddly, when this property is updated by the service, the new value doesn't reflect in the HTML element unless the element is clicked on. I'm perplex ...

Angular2 ERROR: Unhandled Promise Rejection: Cannot find a matching route:

I'm facing an issue with my Angular2 application while utilizing the router.navigateByUrl method. Within my component, there is a function named goToRoute, structured as follows: router.goToRoute(route:string, event?:Event):void { if (event) ...

Learn how to deactivate the pause button with just one click and re-enable it once the popup appears using Angular2 and Typescript

Can anyone assist with solving an issue I am facing with a timer and a pause button? I need the pause button to be disabled once clicked, until a popup appears, then it should become enabled again. My code snippet is provided below: HTML: <button md-i ...

Expanding a JSON type in Typescript to accommodate interfaces

Expanding on discussions about passing interfaces to functions expecting JSON types in Typescript, this question delves into the complexities surrounding JSON TypeScript type. The scenario involves a JSONValue type that encompasses various data types like ...

The test function is not recognized by Cordova when the device is ready

Within my app.component.ts file, I have the following code snippet: export class AppComponent implements OnInit { constructor(private auth: AuthService, private fireBaseService: FirebaseService, ) {} ngOnInit() { this.auth.run(); document.addE ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

Can you explain the functionality of `property IN array` in the TypeORM query builder?

I'm looking to filter a list of entity ids using query builder in an efficient way. Here's the code snippet I have: await this._productRepo .createQueryBuilder('Product') .where('Product.id IN (:...ids)', { ids: [1, 2, 3, 4] ...

Struggling to transfer array data from service to component

I am currently working on passing an array from service.ts to a component. My goal is to display the array elements in a dialog box. However, I encountered a Typescript error TypeError: Cannot read property 'departmentArr' of undefined. I am str ...

Ways to obtain the file path of the compiled worker.js loaded from the worker loader, along with its hash

Currently, I am working on a TypeScript React application that utilizes Babel and Webpack for compilation. I have implemented a rule to load my worker with the following configuration: config.module.rules.unshift({ test: /gif\.worker\.js$/, ...

Encountering a Typescript error with Next-Auth providers

I've been struggling to integrate Next-Auth with Typescript and an OAuth provider like Auth0. Despite following the documentation, I encountered a problem that persists even after watching numerous tutorials and mimicking their steps verbatim. Below i ...