0

Solution to this question How can I merge properties of two JavaScript objects dynamically? explained me how to use spread operator to concatenate two objects in Typescript. But I can't still figure out what will be the type of the object created? I tried

let merged: {o1: obj1, o2: obj2}

but it still gives error Property 'x' does not exist on type {o1: obj1, o2: obj2}. So is there any way we can define type of object created by concatenation?

Vishal Chugh
  • 337
  • 1
  • 6
  • 12
  • 1
    Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Sep 29 '20 at 06:12
  • 1
    I don't see a problem with the [accepted solution](https://www.typescriptlang.org/play?#code/G4QwTgBA9gRgVgRggXggbwgMylAJgLggHIAHASwC8KQiAaCAY3EKOzFyIgF8AoUSWHABMKdBBAA7MgFsQAGxa4oAc068ecgKYAXCNM1hlm3KLQA6C4IT0LZwUK4BuIA) from that post. The type is correctly infered by typescript –  Sep 29 '20 at 06:18
  • @MikeS. OP is more interested in types. In the added link, there is no type given to merged object. – Shivam Pandey Sep 29 '20 at 06:22
  • Property X??? Can you show the line your getting the error? – Keith Sep 29 '20 at 06:34

1 Answers1

1

You can try creating union of two types and assign it as type of merged object.

type Employee = {
    name: string;
    id: number;
};

const employee: Employee = {
    name: 'Shivam',
    id: 1
};

type Address = {
    street: string;
    zip: number;
};

const address: Address = {
    street: 'Aundh, Pune',
    zip: 411007
}

type IUnionEmployee = Employee | Address;

const mergeDetails: IUnionEmployee = {
    ...employee,
    ...address
};

Playground Link: Click here

Shivam Pandey
  • 3,756
  • 2
  • 19
  • 26