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

302
Vistas
How to Set Dynamic Properties to Variable in TypeScript?

I'm trying to set some dynamic properties to a variable in typescript. The problem I'm facing is when I try to set it I run into the error "uncaught TypeError: Cannot set properties of undefined (setting 'varname')" It needs to be set on this variable as it is used to render some other data on the page, I also cannot define a model for the data as I do not know how many properties will be returned or there name/values. How can I assign dynamic properties to my variable. Ex code

// will be dynamic properties in use case
var tValue = 500
var tName = "donuts"
var tArray = [2, 4, 9, 55];

window.onload = (event) => {
let x;
//  trying to set variables will throw error cannot set properties of undefned
x.tree = tValue;
x.header = tName;
x.time = tArray;
} 

Example JS Fiddle: https://jsfiddle.net/mtj6L3zq/

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

0

Just declare x has an empty object.

You probably want a interface as well.

interface SomeObject {
 tree: number;
 header: string;
 time: number[];
}

let x: SomeObject = {}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think this will do what you want:

let x : {[key: string]: any} = {};

You will have to set x to an empty object otherwise you would be trying to access properties of undefined

about 4 years ago · Juan Pablo Isaza Denunciar

0

x is undefined since it is not initialised. hence the error when trying to set the property on x.

Initialising x to an empty object should fix the error.

// will be dynamic properties in use case
var tValue = 500
var tName = "donuts"
var tArray = [2, 4, 9, 55];

window.onload = (event) => {
let x ={} ;
//  trying to set variables will throw error cannot set properties of 
undefned
x.tree = tValue;
x.header = tName;
x.time = tArray;
console.log(x);
} 

Here is a working example.

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