1

I have such an object:

type TransactionType = 'income' | 'expense' | 'transfer' | 'balance'

const transactionTypes: Record<TransactionType, string> = {
  income: 'Income',
  expense: 'Expense',
  transfer: 'Transfer',
  balance: 'Balance',
}

I need to make such a data structure from it:

[
  {value: 'income', label: 'Income'},
  {value: 'expense', label: 'Expense'}
  {value: 'transfer', label: 'Transfer'}
  {value: 'balance', label: 'Balance'}
]

So, I'm adding this function:

function getTransactionTypes() {
  return Object.keys(transactionTypes).map((transactionType) => ({
    value: transactionType,
    label: transactionTypes[transactionType],
  }))
}

And on the line with label: transactionTypes[transactionType], TS throws an error: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<TransactionType, string>'.

Check the sandbox

How could I fix it?

Natalia Davydova
  • 728
  • 7
  • 22
  • 1
    `Object.keys()` returns `string[]` and not `TransactionType[]` because objects are allowed to have extra properties the compiler doesn't know about. If you are positive there are no extra keys, you can use a type assertion like [this](https://tsplay.dev/N9AD7N). See the questions this duplicates for more info. – jcalz May 02 '21 at 14:03

0 Answers0