Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

299
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!