Creating definitions for nested objects in TypeScript

I am dealing with a set of URLs for different buttons. These URLs are requested when the user clicks on one of three buttons: Input, Output, and StandardReport.

The StandardReport button opens a window that contains three more buttons named Define, Validate, and Refresh.

export interface StandardReport {
    define: string;
    validate: string;
    refresh: string;
}

interface GeneratedFilesURL {
  inputs: string;
  outputs: string;
  standardReport: StandardReport;
}

export const GENERATED_FILES_URL: GeneratedFilesURL = {
  inputs: '/generated_files/input_consolidation',
  outputs: '/generated_files/output_consolidation',
  standardReport: {
    define: '/generated_files/standard_report_define',
    validate: '/generated_files/standard_report_validate',
    refresh: '/generated_files/standard_report_refresh',
  },
};

export type Source = 'inputs' | 'outputs' | StandardReport;

To access the URL, I use GENERATED_FILES_URL[source] where source can be either inputs or outputs. When trying to use

Type 'StandardReport' cannot be used as an index type.
, references like
GENERATED_FILES_URL.standardReport.define
or
GENERATED_FILES_URL.standardReport.validate
also cause issues.

I need assistance in fixing the exact structure of the types. Can you help?

Playground link

For detailed error information, please check the errors tab within the playground environment

Answer №1

When defining your Data type, it's important to structure it like this:

export type Data = keyof RetrievedDataMap;
;

To facilitate string lookups in your interface, the best approach is to extend it from Record

interface RetrievedDataMap extends Record<string, any> {
    ....
}

This setup will allow you to easily achieve your desired functionality;

export const dataType: Data = 'customData';
const info = RETRIEVED_DATA_MAP[dataType].info

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 on how to connect several Subjects within an object literal to their corresponding Observables in another object literal

I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject private subjects = { a : new BehaviorSubject<A>(this.a), b ...

Complicated connections between TypeORM and MySQL

Currently leveraging TypeORM in tandem with MySQL, my database comprises of two main Entities, namely User and Project: @Entity() class User { @PrimaryGeneratedColumn('uuid') id: string; @Column({}) name: string; } @Entity() ...

Understanding the attribute types in Typescript React

While working on code using Typescript + React, I encountered an error. Whenever I try to set type/value in the attribute of <a> tag, I receive a compile error. <a value='Hello' type='button'>Search</a> This piece o ...

Can you explain how this promise functions within the context of the mutation observer, even without an argument?

Recently, I came across a mutation observer in some TypeScript code that has left me puzzled. This particular implementation of a promise within the mutation observer seems unconventional to me: const observer = new MutationObserver((mutations: MutationR ...

Is it possible to define an interface to inherit keys from another interface?

I have two different interfaces that I need to align their key structure, but not necessarily the values they hold. One interface (Thing) is sourced from an external library, while the other interface (ThingOptions) is defined in my own project. interface ...

Encountered a hiccup during the installation of ssh2-sftp-client on Next.js

I'm looking for a way to save uploaded files in my domain's storage using SFTP. I came across the multer-sftp package, but when I attempted to run the command yarn add multer-sftp ssh2-sftp-client, I encountered a strange error with the second pa ...

The error message "Property 'name' does not exist on type 'User'" is encountered

When running this code, I expected my form to display in the browser. However, I encountered an error: Error: src/app/addproducts/addproducts.component.html:18:48 - error TS2339: Property 'price' does not exist on type 'ADDPRODUCTSComponent& ...

I seem to be missing some properties in the request body schema. Why am I receiving an incomplete model for

Seeking assistance in grasping the working of models in loopback4. Here's a model I defined: @model() export class ProductViewConfig extends BaseConfig { @property({ type: 'string', id: true, generated: true, }) _id?: strin ...

Is it possible to switch the hamburger menu button to an X icon upon clicking in Vue 3 with the help of PrimeVue?

When the Menubar component is used, the hamburger menu automatically appears when resizing the browser window. However, I want to change the icon from pi-bars to pi-times when that button is clicked. Is there a way to achieve this? I am uncertain of how t ...

Exporting a Typescript interface from a restricted npm package

I'm working on an npm module using TypeScript that includes several interfaces. In the index.ts file, I export all of the classes and interfaces. I defined the interfaces as "interface dto {a:string;} export default dto". However, when I import the ...

Attempting to eliminate any dates that have already occurred

I am faced with an array containing various dates in string format such as "2016-08-12". My goal is to eliminate any dates that have already passed by comparing them to today's date. I am using TypeScript for this task. Here is a snippet of my datoAr ...

Tips for fixing the issue of 'expect(onClick).toHaveBeenCalled();' error

Having trouble testing the click on 2 subcomponents within my React component. Does anyone have a solution? <Container> <Checkbox data-testid='Checkbox' checked={checked} disabled={disabled} onClick={handl ...

"Strange Type Conversion Behavior in next.js 13: Why is res.json() Converting Numbers to Strings

I have encountered a strange issue where no matter what I do, the fetched data is being partially converted to strings. For example, the 'bialko' and 'kcal' fields are supposed to be of type Float in Prisma, yet they are getting casted ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

The JSON.stringify method in TypeScript/JavaScript does not align with the json-String parameter or request body in a Java controller

Currently, I am utilizing jdk 1.8 and have a rest endpoint in my Java controller: @PostMapping("/filters") public ResponseEntity<StatsDTO> listWithFilter( @RequestBody(required = false) String filter ) { try { ............... } } A test sn ...

Unlock the power of TypeScript by linking together function calls

I am looking for a way to create a type that allows me to chain functions together, but delay their execution until after the initial argument is provided. The desired functionality would be something like this: const getStringFromNumber = pipe() .then ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Develop an rxjs pipeline that merges values according to their type prior to executing them in an async manner using concatMap

In my code, there's an eventStream that deals with different types of events and sends them to the server via HTTP. import { from, Observable } from 'rxjs'; import { concatMap } from 'rxjs/operators'; type Update = number[]; inte ...

Guide to integrating a native web component into Vue3

After creating the renderComponent method to display a webcomponent, I attempted to use it in my componentView.vue file. export function renderComponent(el: Element, component: Component,props: VNodeProps,appContext: AppContext){ let vnode: VNode | undefin ...

I'm having difficulty updating the Angular CLI version

I am currently running Angular CLI version 7.1.4 and I have been attempting to update to the latest version. However, each time I try to update, I encounter a multitude of errors. I have attempted using the command ng update @angular/core @angular/cli b ...