Handling Nested JSON with Variable Keys in TypeScript - Runtime Errors
I'm reviewing some code and I'm testing a new approach and I'm refactoring my project and I'm following best practices but I've been working on a project where I need to handle nested JSON objects with variable keys in TypeScript, but I'm working with runtime errors when trying to access certain properties. The JSON structure I receive can vary significantly, and I'm getting `want to read property 'key' of undefined` errors when the expected structure isn't present. Hereβs an example of the JSON I'm dealing with: ```json { "data": { "users": [ { "id": 1, "name": "John", "details": { "age": 30, "address": { "street": "123 Main St" } } }, { "id": 2, "name": "Jane" // Note: details key is missing here } ] } } ``` In my TypeScript code, I'm trying to access the `details` property for each user like this: ```typescript const jsonData = /* JSON data received from API */; const users = jsonData.data.users; users.forEach(user => { const userDetails = user.details; console.log(`User: ${user.name}, Age: ${userDetails.age}`); }); ``` However, this throws an behavior when it encounters a user without the `details` key. I've tried using optional chaining like this: ```typescript const age = user.details?.age; ``` But this just gives me `undefined` and I still don't get to log the age for users that do have the `details` property. Whatβs the best way to handle this scenario so that I can prevent runtime errors and still log the ages of users that have the `details` key? Is there a clean way to filter or map this data without nesting too many checks? I'm using TypeScript version 4.5 and want to maintain type safety as much as possible. I'm on Windows 11 using the latest version of Typescript. Cheers for any assistance! I'm using Typescript 3.11 in this project. I'd be grateful for any help. I recently upgraded to Typescript 3.9.