When typing React component props using TypeScript, I often see code that makes use of optional and nullable fields:type Props = {
href?: string
onClick?: () => void
text: string
}
function Button(props: Props) {
if ('href' in props) {
return (
<a className="Button" href={props.href}>
{props.text}
</a>
)
}
if ('onClick' in props) {
return (
<button className="Button" onClick={props.onClick}>
{props.text}
</button>
)
}
throw ReferenceError('You must pass either href or onClick to <Button />')
}
let a = <Button text="Click me" href="https://github.com" />
let b = <Button text="Click me" onClick={() => {}} />
// OK. Should be an error
let c = <Button text="Click me" href="https://github.com" onClick={() => {}} />
// OK. Throws an error at runtime
let d = <Button text="Click me" />