0

I'm trying to get access to property by string variable in TypeScript. When I write d["account_type"] everything is ok, but when I use one of enums Dictionary and write d[Dictionary.AccountType], I see the error:

Element implicitly has an 'any' type because type 'Dictionaries' has no index signature.

this.dictionaries.toPromise().then(d => { return d["account_type"] });

export enum Dictionary {
    AccountType = "account_type",
    AddressType = "address_type",
    CardBrand = "card_brand",
    ContactType = "contact_type",
    Country = "country",
    DevicePayDay = "device_pay_type",
    LogType = "log_type",
    PaymentProvider = "payment_provider",
    PaymentType = "payment_type",
    Permission = "permission",
    PointProperty = "point_property",
    PointService = "point_service",
    PromoSchemaOn = "promo_schema_on",
    PromoSchemaOff = "promo_schema_off",
    ReportType = "report_type",
}

Is there any way to get access to object properties by enum string value?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
eGrzesiek
  • 21
  • 3
  • Possible duplicate of [TypeScript TS7015 error when accessing an enum using a string type parameter](https://stackoverflow.com/questions/36316326/typescript-ts7015-error-when-accessing-an-enum-using-a-string-type-parameter) – Heretic Monkey Apr 24 '19 at 13:37
  • What is the type of `Dictionaries`? It likely needs to be changed to something like `Record` but you didn't include it here so I don't know how to advise. It helps to provide a [mcve] so others can reproduce the issue and test and suggest a fix. – jcalz Apr 24 '19 at 15:03

1 Answers1

1

Change to

this.dictionaries.toPromise().then((d: any) => { return d[Dictionary.AccountType] });

Demo: https://stackblitz.com/edit/angular-get-value-by-enum

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • This is not a solution, it's a workaround. You're basically making `d` an explicit `any` instead of an implicit `any`. The accepted answer of the duplicate shows how to do this appropriately. – Heretic Monkey Apr 24 '19 at 13:39
  • It works, why it is not proper way? I'm fighting with angular for some time but I don't understund core mechanisms I think:/ – eGrzesiek Apr 24 '19 at 21:35
  • In my opinion it is not workaround, you can use anonymous type for this case and it is simple and common – Hien Nguyen Apr 24 '19 at 21:41