5

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

1
  • 1
    Did you try to type it ? const payments: { [key: string]: {prop1: string} } = {} Commented Dec 7, 2021 at 13:46

1 Answer 1

5

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

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.