Home > Net >  Typescript - Create an object from two objects and set their property names as a value from their ty
Typescript - Create an object from two objects and set their property names as a value from their ty

Time:03-29

I have an object merger inside of a class that currently works like this:

public merge(): TOne & TTwo {
    return { ...this.objectOne, ...this.objectTwo };
}

I am trying to separate them because some properties may have the same name... My first idea was to create 2 variables whose names would be defined by a class property:

public merge(): { [this.objectOne.key]: TOne, [this.objectTwo.key]: TTwo } {
    return { [this.objectOne.key]: { ...this.objectOne }, [this.objectTwo.key]: { ...this.objectTwo } };
}

But that does not work with generic types and shows this error:

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol'

How can I merge them with a custom property name? Or any workaround? Or any suggestion?

PS.: I have just asked this question which I then realized would not be helpful to solve the actual problem.

CodePudding user response:

you can use [key: number]: A | B, any key of the object should be a number or you can specify any type and the value of this key is A or B.

I could not find any way to make dynamic keys like you try to do.

for example :

  type A = {
      key: number;
      name: string;
      age: number;
    };
    
    type B = {
      key: number;
      adress: string;
      phone: number;
    };
    
    const obj1: A = { key: 1, name: "John", age: 30 };
    const obj2: B = { key: 2, adress: "London", phone: 12345 };
    
    const merge = (obj1: A, obj2: B): { [key: string]: A | B } => {
      return { [obj1.key]: obj1, [obj2.key]: obj2 };
    };
    
    merge(obj1,obj2); // {1: {key: 1, name: "John", age: 30}, 2: {key: 2, adress: "London", phone: 12345}}
  • Related