2

I have a value returned to me from a 3rd party within an object which is a string type which I then need to cast as the key of an enum I have defined to reference an enu. Here is my code:

export enum PaymentMethod {
  CASH = 'CASH',
  DD = 'DIRECT_DEBIT',
  UNKNOWN = 'UNKNOWN',
}

export function membershipsTransformer(
  membership: Subscription,
): MembershipDto {
  const {    
    PayementMethodId: paymentType = '',
  } = membership;

  const paymentMethod: PaymentMethod = Object.keys(PaymentMethod).includes(
    paymentType,
  )
    ? PaymentMethod[paymentType]
    : PaymentMethod.UNKNOWN;

As you can see, I check to see if the key exists in the enum then if it does I am trying to then dynamically get the value from the enum with that value to return. I cannot get this to play nicely with Typescript at the moment asI get this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof PaymentMethod'.
  No index signature with a parameter of type 'string' was found on type 'typeof PaymentMethod'.

I have tried the casting the value using

PaymentMethod[paymentType as PaymentMethod] 

and

PaymentMethod[paymentType as unknown as PaymentMethod] 

But neither of these seem to work.

Can anyone offer some advice? Thanks

James
  • 2,800
  • 7
  • 45
  • 81
  • 1
    Does this answer your question? [Element implicitly has an 'any' type because expression of type 'string' can't be used to index](https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b) –  Oct 06 '22 at 07:24
  • 1
    In short, use `PaymentMethod[paymentType as keyof typeof PaymentMethod]` –  Oct 06 '22 at 07:25
  • Please provide reproducible example. WHat is `MembershipDto` and ` Subscription` ? – captain-yossarian from Ukraine Oct 06 '22 at 07:35
  • keyof typeof works thanks! – James Oct 06 '22 at 09:23

0 Answers0