In TypeScript, I have arrays of objects like this
const props1 = [
{ propName: 'id', propValue: 1 },
{ propName: 'name', propValue: 'John' },
{ propName: 'age', propValue: 30 }
];
const props2 = [
{ propName: 'id', propValue: 2 },
{ propName: 'role', propValue: 'admin' }
];
const props3 = [
{ propName: 'job', propValue: 'developer' },
{ propName: 'salary', propValue: 1000 }
];
I want to create a function createObject that I can pass an array of them to it, and it should return an object that its keys are propName with values propValue
This is the desirable results type
const obj1 = createObject(props1); // Returned type should be: { id: number; name: string; age: number }
const obj2 = createObject(props2); // Returned type should be: { id: number; role: string }
const obj3 = createObject(props3); // Returned type should be: { job: string; salary: number }
This is my try, but doesn't return the correct type
function createObject<T extends { propName: string; propValue: any }[]>(propertiesObject: T) {
const obj: { [key: string]: any } = {};
for (const { propName, propValue } of propertiesObject) {
obj[propName] = propValue;
}
return obj;
}