What is the best way to define a category in order to utilize a saved string as a variable for referencing it?

An object named CONFIG holds the following information:

export const CONFIG = {
    buttonDestinations: {
        detailedStats: `detailedStats`,
        mealPlans: `mealPlans`,
        products: `products`
    },
    buttonTexts: {
        detailedStats: `detailed stats`,
        mealPlans: `meal plans`,
        products: `products`
    },
    buttonConfigTypes: {
        detailedStats: `detailedStats`,
        mealPlans: `mealPlans`,
        products: `products`
    },
    navigationVisibilityThreshold: 100
}

This object is later referenced like this:

let configType


switch (true) {
    case elementsVisibility.detailedStats:
        configType = CONFIG.buttonConfigTypes.detailedStats
        break
    case elementsVisibility.selectedMealPlan:
        configType = CONFIG.buttonConfigTypes.mealPlans
        break
    case this.isSelectedProduct:
        configType = CONFIG.buttonConfigTypes.products
    ...
}

if (configType) {
    button.destination = CONFIG[configType].destination
    button.text = CONFIG[configType].text
}

...

However, TypeScript gives a warning:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ buttonDestinations: { detailedStats: string; mealPlans: string; products: string; }; buttonTexts: { detailedStats: string; mealPlans: string; products: string; }; buttonConfigTypes: { detailedStats: string; mealPlans: string; products: string; }; navigationVisibilityThreshold: number; }'.   No index signature with a parameter of type 'string' was found on type '{ buttonDestinations: { detailedStats: string; mealPlans: string; products: string; }; buttonTexts: { detailedStats: string; mealPlans: string; products: string; }; buttonConfigTypes: { detailedStats: string; mealPlans: string; products: string; }; navigationVisibilityThreshold: number; }'.

Any suggestions on how to allow keys of the same object to index it?

Answer №1

To address this issue, you can define configType to represent keys of the CONFIG type by using the following syntax:

const configType: keyof typeof CONFIG;

Another challenge lies in assigning a value to configType while also treating it as a key within the context of CONFIG.

Answer №2

Consider utilizing a const assertion to inform TypeScript that the CONFIG remains constant and is not merely an assortment of strings.

export const CONFIG = {
...
} as const;

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

The expect.objectContaining() function in Jest does not work properly when used in expect.toHaveBeenCalled()

Currently, I am working on writing a test to validate code that interacts with AWS DynamoDB using aws-sdk. Despite following a similar scenario outlined in the official documentation (https://jestjs.io/docs/en/expect#expectobjectcontainingobject), my asser ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

(NextAuth) Error: The property 'session' is not found within the existing type '{}'

While working on a NextJs project with NextAuth, I encountered the following error: "Type error: Property 'session' does not exist on type '{}'.". To resolve this issue, I added the session property to my _app.tsx file as sugg ...

Unexpected expression after upgrading to TypeScript 3.7.2 was encountered, file expected.ts(1109)

After updating TypeScript from version 3.6.x to 3.7.2, I started using optional chaining in my code. However, I encountered a peculiar error. Error message: Expression expected.ts(1109) This error appeared in both my (vim, VSCode) IDE, even though the ...

A Guide to Filtering MongoDB Data Using Array Values

I am trying to extract specific data from a document in my collection that contains values stored in an array. { "name": "ABC", "details": [ {"color": "red", "price": 20000}, {" ...

Using Typescript, a vuex getter that includes an argument can be implemented to

Have you ever wondered how to create a Vuex store getter that takes a parameter argument? Check out this example: https://vuex.vuejs.org/en/getters.html I'm currently working on a project using Typescript (https://github.com/hmexx/vue_typescript_star ...

Can the dimensions of a dialog be customized in Angular Material Design for Angular 5?

I am currently developing a login feature for an Angular 5 application. As part of this, I have implemented an Angular Material Design popup. Within the dialog screen, I have a specific process in place: The system checks the user's email to determi ...

Is there a way to automatically incorporate a component into every view within a Next.js application?

Is there a more efficient and less cumbersome way to import components for every view in a Next.js app? I am interested in incorporating the "arwes" framework into my project and utilizing components from . One of the examples of a component I will be usin ...

Is it possible in TypeScript to change a string literal type into a number type?

Would it be feasible to develop a utility type Number<T> that can take a string literal type and convert it into a number? If conversion is not possible, should the utility return a never type? type Five = Number<'5'> // `Five` is con ...

Angular: Issue with subscribed variable visibility on screen

I am currently developing user management functionality. When a button is clicked, the goal is to save a new user and display an incoming password stored in the system. Below is a snippet of my code: onClick() { /*Code to populate the newUser variable from ...

The Angular TypeScript service encounters an undefined issue

Here is an example of my Angular TypeScript Interceptor: export module httpMock_interceptor { export class Interceptor { static $inject: string[] = ['$q']; constructor(public $q: ng.IQService) {} public request(config: any) ...

Problems related to TypeScript in a callback session

I am currently working on enhancing the API response by adding the unique identifier (id) property during the login process. I followed the recommendation to use callbacks from a discussion on Stack Overflow (Get User ID from session in next-auth client), ...

When the next() function of bcrypt.hash() is called, it does not activate the save method in mongoose

Attempting to hash a password using the .pre() hook: import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2" (<any>mongoose).Promise = require('bluebird'); const user_schema = new Schema({ email: { type: String, required: tru ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...

How to customize the radio button style in Angular 11 by changing the text color

Hey guys, I'm working with these radio buttons and have a few questions: <form [formGroup]="myForm" class="location_filter"> <label style="font-weight: 500; color: #C0C0C0">Select a button: </label& ...

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...

Error in Angular integrating with Stripe. No definition found for 'Stripe'. Perhaps you meant 'stripe'?

I'm currently in the process of connecting Stripe to my app with redirection, utilizing Angular and typescript. My component contains the following code snippet: var head = document.getElementsByTagName('head')[0]; var script = document.cre ...

How can I access the parameter value for the tooltip callback function within echarts?

I am attempting to retrieve the value for this specific Apache EChart from within the callback function of the tooltip formatter. When I manually input the value, the formatting function operates correctly: formatter: (params:any) => `$ ${Math.round(pa ...

Retrieving information from a JSON file utilizing an Interface

For the purpose of learning, I am developing a small Ionic app where I want to load data from a JSON file and map it to an interface that defines the data structure. However, I am facing challenges in achieving this: import { Component } from "@angular/co ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...