TypeScript: Type Inference implementing Union Types in a React Component's Props
After trying multiple solutions online, I still can't figure this out. I'm experiencing a frustrating scenario with TypeScript's type inference when using union types for props in a React component. I have a component that accepts a prop which can be either a string or an object containing a `name` property. However, TypeScript seems to struggle to infer the prop type correctly, leading to some unexpected behavior. Hereβs the relevant code snippet: ```typescript interface UserProps { user: string | { name: string }; } const UserDisplay: React.FC<UserProps> = ({ user }) => { return ( <div> {typeof user === 'string' ? user : user.name} </div> ); }; ``` When I try to use this component with a string, it works fine: ```typescript <UserDisplay user="John Doe" /> ``` But when I pass an object: ```typescript <UserDisplay user={{ name: "Jane Doe" }} /> ``` I get the following TypeScript behavior: `Type 'string | { name: string; }' is not assignable to type 'string'.` This seems to suggest that TypeScript doesn't recognize that I've already checked the type of `user` before accessing `user.name`. I've tried adding a type assertion as follows, but it didn't resolve the scenario: ```typescript const UserDisplay: React.FC<UserProps> = ({ user }) => { return ( <div> {typeof user === 'string' ? user : (user as { name: string }).name} </div> ); }; ``` The behavior continues. Iβm using TypeScript 4.5.4 and React 17.0.2. Can anyone suggest how I can get TypeScript to correctly infer the types here? Is there a better way to handle this scenario that avoids these type errors? Any insights would be greatly appreciated! My development environment is Windows. Am I missing something obvious?