Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
Create an object from two objects and set their property names as a value from their type definitions

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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}}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda