0

I'm struggling with defining type for accumulator in array reduce method.

  private buildRequestBody(payoutFields: IWithdrawalRequest): ISignedWithdrawalRequest {
    const sortedPayoutFieldKeys = Object.keys(payoutFields)
      .sort() as Array<keyof IWithdrawalRequest>;

    const requestBody = sortedPayoutFieldKeys.reduce((acc: Partial<IWithdrawalRequest>, key) => {
      acc[key] = payoutFields[key] ;
      return acc;
    }, {});

    ...
  }

It keeps throwing a typescript error for acc[key]

TS2322: Type 'string | number' is not assignable to type 'undefined'.   Type 'string' is not assignable to type 'undefined'.

3
  • If you've solved your own problem do you want to post it as an answer instead of just as a comment? Commented Nov 6, 2022 at 20:31
  • I struggle to understand the point of your code. You're basically cloning payoutFields, right ? why do you bother to sort its properties ? anyway, if you must do this sorting, you could at least use Object.fromEntries to replace that old accumulator pattern, which would remove your typing issue altogether and improve efficiency. Commented Nov 6, 2022 at 21:59
  • It is one of the most ubiquitous patterns when dealing with payment provider integration. Anyway thank you! Commented Nov 6, 2022 at 22:04

1 Answer 1

0

This is an ok solution for now:

const requestBody = sortedPayoutFieldKeys.reduce(
  (acc: Partial<IWithdrawalRequest>, key) => {
    (acc[key] as unknown) = payoutFields[key];
     return acc;
  },
{});

better than using "any".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.