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