How to Type a Function that Accepts Multiple Different Object Shapes in TypeScript?
I'm reviewing some code and I'm relatively new to this, so bear with me... I'm working on a TypeScript project where I need to create a function that can accept objects of various shapes, specifically for processing user data and order data. My current implementation looks like this: ```typescript interface User { id: number; name: string; email: string; } interface Order { orderId: number; userId: number; total: number; } function processData(data: User | Order) { if ('email' in data) { console.log(`Processing user: ${data.name} (${data.email})`); } else if ('orderId' in data) { console.log(`Processing order: ${data.orderId} for user: ${data.userId}`); } } ``` This code works as expected, but I noticed that TypeScript gives me an error when I try to call this function with an object that doesnโt conform exactly to either interface. For example: ```typescript const invalidData = { id: 1, name: 'Alice' }; processData(invalidData); // Error: Argument of type '{ id: number; name: string; }' is not assignable to parameter 'data'. ``` I want to allow some flexibility, so I was thinking about using a generic type or a union type with more optional properties. However, Iโm unsure how to implement it correctly without losing type safety. I also want to ensure that if the object has properties not defined in either interface, TypeScript should still flag it as an error. Whatโs the best approach to achieve this while maintaining type safety? Any suggestions on how to refine my types or my function implementation would be greatly appreciated! Thanks in advance! This is happening in both development and production on Ubuntu 22.04. Any advice would be much appreciated.