How to dynamically add properties to an object in TypeScript (without type errors)
Hi everyone! I recently started learning TypeScript and encountered a problem that puzzled me a lot. I need to create objects whose properties are added dynamically during program execution.\n\nHere's an example: I receive data from an API in JSON format, but the response structure can change. I want to create an empty object and then fill it with properties based on the received data. In regular JavaScript this is done easily:\n\n```typescript\nconst data = {};\ndata.name = "John"; // works\ndata.age = 30; // works\n```\n\nBut when I try to do the same in TypeScript, the compiler throws an error: "Property 'name' does not exist on type '{}'". TypeScript complains that the `data` object has type `{}` and it doesn't have such properties.\n\nI tried different options:\n- Declaring the object via
No answers yet.
Log in to leave an answer
Blogs
Swift vs Python for Backend: What to Choose in Practice in 2024
Monorepository with Go: Code Organization for Beginners
Embedded C++: How to Write Code for Microcontrollers Without Losing Your Mind
How to add a placeholder to UITextView in Swift: a complete guide