I have the following typescript code:
const a = [{ foo: 1 }, { bar: '2' }]
I wish to use a
to create an object of the form:
const b = {
foo: 1,
bar: '2'
}
and the typing of b
should be equivalent to the type:
type EquivalentType = {
foo: number
bar: string
}
Is this possible without casting? How can this be done?
CodePudding user response:
if you want this to be dynamic meaning you don't know what properties will be in the array you can do something like this:
const a = [{ foo: 1 }, { bar: '2' }]
let b = {};
for (let obj of a) {
for (let property in obj) {
b[property] = obj[property];
}
}
console.log(b)
CodePudding user response:
// You might be able to simplify this
type TypeFromLiteral<T> = T extends string ? string : T extends number ? number : T extends boolean ? boolean : never;
// The "as const" part is important so that we can process the types
const a = [{ foo: 1 }, { bar: '2' }] as const;
// Get the final type
type ObjectUnion = typeof a[number];
type NewType = { [T in ObjectUnion as keyof T]: TypeFromLiteral<T[keyof T]> };
// By itself, this will get the correct value. However, we need to process the type separately and cast it to get what you want.
const b = Object.assign({}, ...a) as NewType;