1

Why does the key of [type] need a type? It's really weird to say that, but I have a problem.

data example:

export enum ENUM_Bike {
 suzuki   = 'suzuki',
 yamaha   = 'yamaha',
 kawasaki = 'kawasaki'
}

export type TBike_StringMapping = { [key in ENUM_Bike]: string };

export const CONST_BikeIconName: Readonly<TBike_StringMapping> = {
 suzuki   : 'icon_a',
 yamaha   : 'icon_b',
 kawasaki : 'icon_c',
}

export const CONST_BikeIconColor: Readonly<TBike_StringMapping> = {
 suzuki   : '#111',
 yamaha   : '#222',
 kawasaki : '#333',
}

using

<mat-icon
 *ngFor="let item of CONST_BikeIconName | keyvalue: orderByJson"
 [ngStyle]="{'background-color': CONST_BikeIconColor[item.key] }">
    {{ item.value }}
</mat-icon>

I have been using it like this, but now it appears

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Readonly<TBike_StringMapping>'. No index signature with a parameter of type 'string' was found on type 'Readonly<TBike_StringMapping>'.ts(7053)

I found a discussion, but it can't solve my problem. I need type not interface. Can anyone help me? thanks for the help.

TypeScript TS7015 error when accessing an enum using a string type parameter

Edit to Rachid O: there has same example here, and same error

error example on typescriptlang.org

Pork Jackson
  • 339
  • 1
  • 15

1 Answers1

1

one quick solution for this problem would be to exactly do what the compiler suggests and add an intermediate type that has an index signature like so :

export interface TBike_StringMappingExtended extends TBike_StringMapping {
    [key: string]:string
}

this will give :

export enum ENUM_Bike {
 suzuki   = 'suzuki',
 yamaha   = 'yamaha',
 kawasaki = 'kawasaki'
}

export type TBike_StringMapping = Record<ENUM_Bike, string>;

export interface TBike_StringMappingExtended extends TBike_StringMapping {
    [key: string]:string
}

export const CONST_BikeIconName: TBike_StringMappingExtended = {
 suzuki   : 'icon_a',
 yamaha   : 'icon_b',
 kawasaki : 'icon_c',
}

export const CONST_BikeIconColor: TBike_StringMappingExtended = {
 suzuki   : '#111',
 yamaha   : '#222',
 kawasaki : '#333',
}

for (let key in CONST_BikeIconName) {
    if (key) {
    const element = CONST_BikeIconColor[key];
    }
}
Rachid O
  • 13,013
  • 15
  • 66
  • 92
  • Great answer, this gave me a new understanding of the usage of types and interfaces. In addition, I found that if I use value as an index in the loop of html, the error will not appear. – Pork Jackson Jan 20 '21 at 18:45
  • If use your solution, no matter whether use key or value as an index in the html loop, no error will occur. – Pork Jackson Jan 20 '21 at 18:47