Specify the key type when using the syntax "key in ObjectName"

I need assistance in setting the key type of an object. Here is what I have tried:

type TypeSample = {
    [key: string]: string
}

In addition, I want to specify that the keys should come from an enum like this:

enum EnumSample {
    'ok' = '200',
}

type TypeSample = {
    [key in EnumSample]: string
}

If I do not set the key type, I encounter the error

'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'TypeSample'
when using my "getter" function.

My Inquiry: How can I adjust "TypeSample" so that TypeScript recognizes it will only contain string keys?

Please note: It is crucial for other parts of the code that "EnumSample" remains an ENUM and not a TYPE/INTERFACE.


Context:

Here is a simplified version of the code I am dealing with:

enum SupportedHttpStatuses {
    'ok' = '200',
    'badRequest' = '400',
    'imATeapotSafe' = '418a',
    'imATeapot' = '418b',
}

type StatusMapType = {
    [key in SupportedHttpStatuses]: StatusType // My aim is to define the key type here
}

type StatusType = {
    code: number, // status code to send to the browser
    title: string, // error title
    description: string // error description
}

class Test {
    public static STATUS_MAP: StatusMapType = {
        '200': {
            code: 200,
            title: 'OK',
            description: 'This request has succeeded.',
        },
        '400': {
            code: 400,
            title: 'Bad Request',
            description: 'This request is missing data or contains invalid information.',
        },
        '418a': {
            code: 200,
            title: 'I\'m A Teapot!',
            description: 'This request was successful but it is april fools day.',
        },
        '418b': {
            code: 418,
            title: 'I\'m A Teapot!',
            description: 'This request was successful but it is april fools day.',
        },
    }

    public static async getStatusMap(statusId: string): Promise<StatusType> {
        return this.STATUS_MAP[statusId] // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'StatusMapType'
    }
}

Answer №1

My recommendation would be to update the function signature of

getStatusMap(statusId: string): Promise<StatusType>

to

getStatusMap(statusId: SupportedHttpStatuses): Promise<StatusType>

By making this change, the code will ensure that STATUS_MAP[statusId] recognizes statusId as a SupportedHttpStatuses. Consequently, when STATUS_MAP is accessed by index, it will return a corresponding StatusType.

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

Setting up types for variables in Angular 2 componentsHere is an

I have a model that consists of multiple properties, and I aim to set all these properties with a default value of either empty or null. Here is an example of my Model: export class MyModel { name: string; jerseyNumber: number; etc... } In m ...

Data fetched using React Query

When using React Query to fetch data, the function runs smoothly. After console.logging the 'data' variable from React Query, it prints an array of objects as expected and handles states efficiently between loading, success, error. The issue ar ...

How can we optimize ternary statements within ternary statements in Type Script and React Native for best practices?

Can you help me optimize this code snippet that uses nested ternary operators for better readability and correctness? <TouchableOpacity style={ darkMode ? filterState === 'A' ? styles.activeButtonDark : styles.buttonDa ...

[deactivated]: Modify a property's value using a different component

One of the requirements for my button is that it should be disabled whenever the callToActionBtn property is true. match-component.html <button [disabled]="callToActionBtn" (click)="sendTask()>Send</button> match-component.ts public callToA ...

Angular Material's input field is not correctly binding to localeString

I'm currently utilizing Angular Material 11.2, and I have a specific need to convert the inputted string into US dollars format. My attempts so far include: <input matInput formControlName="test" (onkeyup)="onKeyUpTest($event)" ...

The Type '{Property: string, Property2: string} does not match the type Observable<Filters[]>

Here is a method I am trying to use: getFilters(): Observable<Filters[]> { let filters: Observable<Filters[]> = [ { property: "Value", property2: "Value2" }, { property: "Value3", property2: "V ...

Ways to properly assign a key in a Generic Interface as the interface key

Can someone assist me with TypeScript generics? I am wondering how to access the T["value"] field within the ActionAdd interface. type UserValue = { username: string; }; interface User { id: number; value: UserValue; } interface ActionAdd<T = unkn ...

Retrieving the component's values when utilizing the `<ng-content>` directive

Seeking a technique for accessing the values of a component when utilizing <ng-content>: import {Component} from '@angular/core'; @Component({ selector: 'home-page', template: `<person-box>{{name}}</person-box> & ...

What is the best way to access the input element of ng-content from the parent component?

Creating a unique component in the following structure <div class="custom-search-field" [ngClass]="{'expanding': expanding}"> <ng-content></ng-content> </div> When using this component, users are expected to include ...

Retrieve data from a Firestore document in an Ionic application

I have a service that retrieves a specific document from Firestore using the getBidremains method. The method in the TypeScript class is called in ngOnInit like this: this.userInfo = this.firestoreService.getBidremains(userId).valueChanges().subscribe(da ...

Troubleshooting TypeScript errors in Cassini with Google Chrome

While troubleshooting a .NET 4.6.1 web application with Cassini in Visual Studio 2015 version 14, update 3, I encountered an error on a page that utilizes TypeScript: Refused to execute script from 'http://localhost:53049/Scripts/app.ts' because ...

Implementing unique behaviors based on data types in Typescript

I'm currently working on a React project where I need to showcase different types of articles, which I refer to as "Previews." These articles can be either text-based or contain images/videos. To handle this, I've defined two interfaces (TextPre ...

The functionality of Angular/Typescript class.name appears to fail during a production build

Using Angular 5, I encountered an unusual problem with the class.name property. We have a TypeScript function as shown below: export class ApiService { public list<T>(c: new(values: Object)=> T) { var cname = c.name; .... } } When ...

Struggling with TypeScript Errors while Extending Theme Colors in Material UI React using TypeScript

Just started with typescript and feeling a bit lost, can someone offer some guidance? I'm working on a React project using material-ui with typescript. To add a new color the correct way, it needs to be added to a theme: const theme = createMuiTheme({ ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

Creating a JSON schema for MongoDB using a TypeScript interface: a step-by-step guide

In order to enhance the quality of our data stored in MongoDB database, we have decided to implement JSON Schema validation. Since we are using typescript in our project and have interfaces for all our collections, I am seeking an efficient method to achie ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

Using React to iterate over an array of objects and generate Date TextFields in Material UI

I have an array of objects representing different stages in a specific process, each stage identified by an id and name. The structure of the array is as follows: const stages = [ { id: 1, name: initialize }, { id: 2, name: execute ...

What is the best way to retrieve an object when a value is not found? Consider implementing a looping mechanism with a specific condition in React and TypeScript to successfully

Greetings, I am faced with an array of objects structured as follows: const arr_obj = [ { id: '1', jobs: [ { completed: false, id: '11', run: { ...

I am continuously receiving the message "Alert: It is important for every child in a list to possess a distinct "key" prop." while working with the <option> list

Having trouble generating unique keys for my elements. I've tried different values and even Math.random() but still can't seem to get it right. I know the key should also be added to the outer element, but in this case, I'm not sure which on ...