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

128
Vistas
Typescript - Custom type assignment by value

In one of my procedures I need to periodically reset a custom type, but I noticed that in TypeScript (and I think in JavaScript too maybe), when I assign a variable of a custom type to another variable of the same type, the assignment is made by reference and not by value.

For example this code:

type testing = {
    a: string;
    b: number;
};

let v1: testing = { a: "one", b: 1 };
let v2: testing = { a: "two", b: 2 };

console.log(v1);
console.log(v2);

v1 = v2;
v1.a = "Edited";

console.log(v1);
console.log(v2);

generates this output

{ a: 'one', b: 1 }
{ a: 'two', b: 2 }
{ a: 'Edited', b: 2 }
{ a: 'Edited', b: 2 }

Is there a way to assign it by value without assigning every property of the type?

(in my example I need my v2 variable to remain equals to { a: "two", b: 2 })

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

0

For simple cases like this, you can make use of the spread operator to create a shallow copy of an object.

type testing = {
    a: string;
    b: number;
};

let v1: testing = { a: "one", b: 1 };
let v2: testing = { a: "two", b: 2 };

console.log(v1);
console.log(v2);
// copy all of the top-level keys and values from v2 
// into a new object and assign that to v1
v1 = { ...v2 }; 
v1.a = "Edited";

console.log(v1);
console.log(v2);

Note there are some caveats here. As indicated by the link in Tobias S' comment, this will only do a shallow copy. If you have more complex objects, this will cause issues.

let v1: testing = { a: "one", b: 1, c: { d: 1 } };
let v2: testing = { a: "two", b: 2, c: { d: 2 } };

v2 = { ...v1 };
// v1.c is the same object as v2.c because we only shallowly
// copied, so this assignment is reflected in both
v2.c.d = 60;

console.log(v1);
console.log(v2);
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