I have some types defined as following:
type SomeData = {
field1?: string;
field2?: string;
}
interface User {
name?: string;
enabled?: boolean;
someData?: SomeData;
}
interface InitValue {
name: (string | undefined)[];
enabled: (boolean | undefined)[];
someData: (SomeData | undefined)[];
}
and some variables that uses these types:
let values: InitValue = {
name: [],
enabled: [],
someData: []
}
const users: User[] = [
{
name: 'A',
enabled: true,
},
{
name: 'B',
enabled: false,
someData: {
field1: 'field1 value'
}
}
]
I want from users
to fill my values
object like following:
users.forEach((user)=> {
for (const [key, value] of Object.entries(user)) {
values[key].push(value)
}
})
But this generates me a typescript error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'InitValue'.
No index signature with a parameter of type 'string' was found on type 'InitValue'.
it’s because Object.entries
didn’t return the types of user
.
If I use a switch statement this will work:
users.forEach((user)=> {
for (const [key, value] of Object.entries(user)) {
switch (key) {
case 'name':
values[key].push(value)
break;
case 'enabled':
values[key].push(value)
break;
}
}
})
but I dont want to use it, since in real data I have there is more than 100 fields and I don’t want to repeat that for every single key.
What I want is to resolve the type of key
and value
.
How can I solve this?
here is the full TS Playground: