TypeScript and React: Generic Component Prop Types Not Inferring Correctly with Conditional Rendering
I'm working on a generic React component in TypeScript that conditionally renders either a button or a link based on the prop type I pass... However, I am working with an scenario where TypeScript is not inferring the properties correctly for the conditional types. My component takes a generic type `T` and I want to ensure that if `T` is a specific type, it renders a link with `href`, otherwise it should render a button with an `onClick` handler. Hereโs the code I currently have: ```tsx import React from 'react'; type ButtonProps = { onClick: () => void; label: string; }; type LinkProps = { href: string; label: string; }; type Props<T> = T extends 'link' ? LinkProps : ButtonProps; const CustomComponent = <T extends 'button' | 'link'>(props: Props<T> & { type: T }) => { if (props.type === 'link') { return <a href={props.href}>{props.label}</a>; } else { return <button onClick={props.onClick}>{props.label}</button>; } }; export default CustomComponent; ``` When I try to use this component like so: ```tsx <CustomComponent type="link" href="https://example.com" label="Example Link" /> <CustomComponent type="button" onClick={() => alert('Clicked!')} label="Example Button" /> ``` TypeScript is throwing a type behavior for the `href` property when using the link, saying it does not exist on type 'ButtonProps'. I expected TypeScript to narrow down the props automatically based on the `type` prop. I even tried adding a conditional type check inside the component, but it still doesn't seem to resolve the scenario. Is there a better way to structure this so that TypeScript can recognize the correct prop types based on the componentโs type prop? This issue appeared after updating to Typescript 3.10. Am I approaching this the right way?