TypeScript: How to Properly Handle Optional Chaining with Strict Null Checks in a Redux Store?
I've been researching this but I'm dealing with I'm working on a project and hit a roadblock... I'm deploying to production and Quick question that's been bugging me - I'm relatively new to this, so bear with me. I am working on a React application using TypeScript and Redux, and I'm working with an scenario with optional chaining when trying to access deeply nested properties in my Redux store. I have my TypeScript configuration set with `strictNullChecks` enabled, which is great for catching potential issues, but it's causing problems when I access optional properties. For example, I have a state shape like this: ```typescript interface User { id: number; name: string; preferences?: { theme?: string; }; } interface AppState { user?: User; } const initialState: AppState = {}; ``` When I try to access the theme property like this: ```typescript const theme = state.user?.preferences?.theme; ``` TypeScript gives me an behavior saying: `Object is possibly 'undefined'.` However, I thought optional chaining would prevent this behavior. I have tried using type assertions, like so: ```typescript const theme = (state.user?.preferences as { theme?: string })?.theme; ``` But this leads to another warning about using type assertions. I’ve also considered adding default values with nullish coalescing: ```typescript const theme = state.user?.preferences?.theme ?? 'default-theme'; ``` This works, but I’m still worried about the implications of strict null checks and whether I’m following best practices. Is there a better way to handle optional properties in this kind of scenario while adhering to strict null checks? What would be the recommended approach to ensure that my code is both safe and clean? Any insights would be greatly appreciated! What's the best practice here? I'd really appreciate any guidance on this. This is my first time working with Typescript 3.9. Is there a better approach? I'm on macOS using the latest version of Typescript. Has anyone dealt with something similar? I've been using Typescript for about a year now. How would you solve this? This is for a service running on Ubuntu 22.04. I'd be grateful for any help. I'm developing on CentOS with Typescript. Am I approaching this the right way?