TypeScript: How to correctly infer types for a dynamic configuration object in a library?
After trying multiple solutions online, I still can't figure this out. I've looked through the documentation and I'm still confused about I'm working on a TypeScript library that allows users to pass a dynamic configuration object. However, I'm struggling with how to infer types based on certain keys within that object. For example, I want to ensure that if a user specifies a `database` key in their configuration, they must provide additional keys like `host`, `port`, and `username`. I've tried using mapped types, but I'm running into issues with TypeScript not inferring the types correctly. Here's a simplified version of what I have: ```typescript interface Config { apiKey: string; database?: { host: string; port: number; username: string; }; } function initialize(config: Config) { if (config.database) { console.log(`Connecting to database at ${config.database.host}:${config.database.port} as ${config.database.username}`); } else { console.log('No database configured.'); } } ``` The question arises when I try to enforce that if `database` is provided, all its necessary fields must be included. If a user only provides `database: { host: 'localhost' }`, TypeScript doesn't throw an behavior, even though `port` and `username` are required for a valid configuration. I tried using a union type approach but it's getting complicated with other optional keys in the configuration. Whatβs the best way to enforce these nested requirements while keeping user-friendliness in mind? Any insights or examples would be greatly appreciated! I'm using TypeScript 4.5.2. I'd really appreciate any guidance on this. How would you solve this?