0

I'm trying to reduce Object.keys, like this:

const example = { hello: true }
Object.keys(example).reduce((acq, key) => {
  const value = example[key]
  return acq
}, {})

For some reason I am getting a type error under example[key]

(parameter) key: string

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

I created my own getKeys function with a generic that has the typings I'd expect:

function getKeys <T>(g: T) {
  return Object.keys(g) as (keyof T)[]
}

const example = { hello: true }
getKeys(example).reduce((acq, key) => {
  const value = example[key]
  return acq
}, {})

However I'm looking if this is possible without wrapping Object.keys.

1

1 Answer 1

1

In this case you could provide a for your example variable as shown below to let typescript know that the keys are of type string.

const example = { hello: true } as { [key: string]: 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.