LWang
LWang

Reputation: 95

Typescript: typing an object with dynamic properties

I want to loop an array to create an object.

input:

const input = [{email:email1, name: name1},{email:email2, name: name2}, {email:email3, name: name3}]

Desired output:

const output = {email1: name1, email2: name2, email3: name3
}

In javascript, I wrote

 let output = input.reduce((acc, cur, i) => {
                return (acc[cur.email] = cur.name)
            }, {})

But I got a typing error saying obj cannot have a string property. How should I type this function properly?

Upvotes: 1

Views: 258

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249476

You need to be more explicit about the type of the result, typescript will not know that {} is supposed to be an object with any keys strings and string values:

const input = [{ email: 'email1', name: 'name1' }, { email: 'email2', name: 'name2' }, { email: 'email3', name: 'name3' }]
let output = input.reduce<Record<string, string>>((acc, cur, i) => {
    acc[cur.email] = cur.name
    return acc;
}, {})

Note: Also you need to return acc from the reducer function.

Upvotes: 1

Related Questions