1

I'm trying to loop through an object which holds a number of properties and the value is always an array of numbers. When I try to run the code below I get the error:

property 'length' does not exist on type 'unknown'

When using Typescrip how do I assign a types when the object key/value pair is destructured in this way?

Thanks

  for (const [key, value] of Object.entries(object)) {
      console.log(value.length)
   }

1
  • 2
    What’s the type of object/where does it come from? Ideally it would have a type that would encode that knowledge, so you don’t have to do anything on the loop side, but the best way to do that depends on the situation. Commented Mar 22, 2022 at 19:26

1 Answer 1

1

You can add a type to the object beforehand.

const object: Record<string, number[]> = {}

for (const [key, value] of Object.entries(object)) {
  console.log(value.length)
}

Read more about the Record utility type here

You can also type cast the object instead.

for (const [key, value] of Object.entries(object as Record<string, number[]>)) {
  console.log(value.length)
}

See all the examples in TS playground here

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.