Transforming TypeScript class of methods into a dictionary-style object

I've been working on a TypeScript project and am looking to improve the structure of some elements we're using. There is a file that's currently defined as a class, but I think it could be simplified down to a basic dictionary/POJO. Here's how it's currently set up:

export class AppSettings{
    public static get API(): string { return '/apis';}
    public static get API_COMMON(): string {return `${this.API}/common`;}
    public static get API_COMMON_VENDORS(): string {return `${this.API_COMMON}/vendors`;}
    //...redacted for brevity...
    //... return `${PREVIOUS_API_GET}/nextURL`....
}

The desired end result is to access the values through indexing on the object. (e.g.

AppSettings['domain']['endpoint']
)

In essence, our app has different "areas" or "domains" that perform similar functions but cater to varying use cases. For instance, we have an admin portal and a client-facing app, both dealing with the same types of data (invoices, batches, purchase orders, etc.). So, just to clarify, a practical example would look like

AppSettings['admin']['getBatches']
or
AppSettings['customer']['getBatches']

So, my question is: How can I go about refactoring this setup?

Answer №1

To define functions or objects, you can do it like this:

const API = (): string => '/apis';
const API_COMMON = (): string => `${this.API}/common`;
const nested_obj = { prop: 'thing' };
....

After defining them, you can export all of them (optionally as the default too):

export {
  API,
  API_COMMON,
  nested_obj
  ...
};

When you import the object, you can use it as a dictionary or object.

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

Ways to adjust the HTMLElement in index.html prior to sending the page back to the requester

I have been working on dynamically modifying a meta tag based on custom URL parameters that I process. In my index.html file, I have identified the meta tag like this: <meta name="og:image" content="http://example.com/someurl.jpg" id="ogImage"/> Th ...

The absence of a 'defaultValue' argument in Typescript React is causing an issue

I'm encountering an issue with my code. The error message states "An argument for 'defaultValue' was not provided." I am trying to set default values but unsure of what those values should be. Additionally, I am facing a couple of other err ...

Uncovering the Image Orientation in Angular: Is it Possible to Determine the Direction Post-view or Upon Retrieval from Database?

I am currently working on creating centered and cropped thumbnails for images retrieved from a database. I came across some helpful information on how to achieve this: The resource I found is written for JavaScript, but I am using Angular 7. I am facing d ...

What is preventing TypeScript from identifying the type of a parent based on its child?

Take a moment to explore the following example: type Num = { type: 'NUMBER' numberValue: number } type Str = { type: 'STRING', stringValue: string } type B_Num = { a: Num; numberData: number; } type B_Str = { ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Typescript encounters an error when attempting to access a property of an undefined

Encountered a TypeError: Cannot read property 'ghNewPrMethod' of undefined Every time I attempt to send a webhook POST to my Typescript application, the error mentioned above pops up. Here is the snippet of code from the controller: import { G ...

Troubleshooting the issue with integrating a user-defined Cordova plugin in Ionic 2 using TypeScript

I have developed a custom Cordova plugin and I am trying to integrate it with an Ionic 2 project that is using TypeScript and Angular 2. While I have successfully added the plugin to the Ionic 2 project, I am facing issues when trying to call methods defin ...

Use the IONIC CAPACITOR application to send a 20-byte command to a BLE device

Hello everyone, I am currently working on an application that is designed to connect to a BLE device. I have a requirement to write 20 Bytes to the device using BleClient.write function. 34h 01h 50h 4Fh 4Ch 49h 54h 45h 43h 00 00 00h 00h 00h 00h 00h 00h 00h ...

Error Encountered: Module Not Found - Ionic Version 2

I have been working on a project using Ionic 2, with the initial page set to AuthPage. I recently added a new page called SplashPage through the console. However, when I tried setting the rootPage to SplashPage, I encountered an error stating Uncaught Erro ...

Implement a function to delete an item from an array within a React object by utilizing the UseState hook

I am facing a challenge in React as I attempt to remove an element from an array within an array of objects using the UseState hook. Despite my efforts, the interface does not re-render and the object remains in place. From what I understand, in order for ...

TypeScript error: Attempting to assign a value to this.x within the class constructor is not allowed

interface ClassInterface { panelWidth: number; panelHeight: number; }; class Panels<ClassInterface> { constructor(panelWidth: number, panelHeight: number) { console.log(panelWidth); // 820 console.log(panelHeight); // 62 ...

Angular 6: TypeError - The function you are trying to use is not recognized as a valid function, even though it should be

I'm currently facing a puzzling issue where I'm encountering the ERROR TypeError: "_this.device.addKeysToObj is not a function". Despite having implemented the function, I can't figure out why it's not functioning properly or callable. ...

Displaying notification in Ionic 2

Whenever I click on the register button, if I fill out all the fields I am taken to the regsuccess page. Otherwise, I receive a message saying to fill in all required fields. However, I want to display an alert message using Ionic2 and TypeScript. HTML: ...

I'm perplexed as to why I'm receiving null for my context. Could it be due to a TypeError

Recently diving into Next Js and TypeScript, I encountered the following error: Unhandled Runtime Error TypeError: this.context is null Here's a snippet from my Layout.tsx file: import { FC } from 'react' import { Head } from 'next/d ...

Navigating through a complex array structure and having the capability to both search and filter its elements

hi there! I'm reaching out for some assistance with a challenge that I've encountered. Currently, I am working on developing a dashboard that iterates through criminal charges. I have structured the database table as follows: category charges ...

Enable lazy loading to retrieve the current routed module

I'm currently working on a way to exclude a component when a specific module is routed in a lazy loading application. For instance, in my AppComponent I have a router-outlet and a component above it: <div> <my-component></my-compo ...

Having trouble finding the "make:migration" command in Adonis 5 - any suggestions?

After reviewing the introductory documentation for Adonis Js5, I attempted to create a new API server. However, when compiling the code using "node ace serve --watch" or "node ace build --watch", I kept receiving an error stating "make:migration command no ...

I attempted to unsubscribe from an observable in Angular, but I encountered an error stating that the unsubscribe function does not exist

Here is the code snippet from a components.ts file in an Angular project. I encountered the following error during compilation: ERROR merge/merge.component.ts:75:12 - error TS2551: Property 'unsubscribe' does not exist on type 'Observable& ...

Implementing Server-Side API Response Caching in React-Query and Next JS

My server-side rendering setup with react-query is working smoothly. I am aware that react-query stores a cache on the client side to serve data if the query key is fresh and available. Here is the code snippet depicting this setup - // pages/_app.tsx imp ...

Double up on your calls to the subscribe function in Angular to ensure successful login

Within my angular 7 application, there is a sign in component that triggers the sign in function within the authentication service. This function initiates an HTTP post request and then subscribes to the response. My goal is to have both the auth service f ...