Home > Enterprise >  Typescript get object value from key
Typescript get object value from key

Time:12-08

How to get the property using the index of the key of an object in typescript?

Despite the error on TypeScript, the code works correctly.

My code

const payments = {
  KEY1: {prop1: "prop1"},
  KEY2: {prop1: "prop1"}
}

When I try to access by key value I got the error

const index = 0

const key = Object.keys(payments)[index]
const payment = payments[key] // ERROR HERE

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)

payments is of type object

CodePudding user response:

Add this

const key = Object.keys(payments)[index] as keyof typeof payments;

When you don't explicitly declare type for payments, typescript inferred as specific keys(KEY1 and KEY2)

and Object.keys() returns type as string that leads to error.

The above line I modified will tell typescript that key will be keys of payments and not string.

You can read more about this here Creating Types from Types

  • Related