How to iterate through an object and modify it without losing types

Viewed 43

I have typed an object that I want to iterate through and do something to each value and then reconstruct the object without losing its typing and want to do this without mutating anything.

This is what I am trying right now:

type myObj = {
    arr1: number
    arr2: number
}

const c: myObj = {arr1: 1, arr2: 1}

const d: myObj = Object.entries(c)
.map(entry => {
    const prop = entry[0]
    const value = entry[1]

    return {[prop]: value} // do something to value here
})

// recombine all the objects into the arrObj structure
.reduce((a, e) => {return {...a, ...e}}, {})

d would have the correct property names and value types and of myObj, yet typescript gives the error

Type '{ [x: string]: number; }' is missing the following properties from type 'myObj': arr1, arr2

How can I modify this?

1 Answers

I tried many things to solve this but came to the conclusion that Object.entries is the problem.

This post describes a workaround to type up Object.entries (also I have just seen jcalz comments): https://stackoverflow.com/a/60142095/4529555

Pay particular attention to this part:

In this case Object.entries would return an array containing the element ['d', false]. The type Entries says this cannot happen, but in fact it can happen; so Entries is not a sound return type for Object.entries in general. You should only use the above solution with Object.entries when you yourself know that the values will have no excess properties; Typescript won't check this for you.

Related