I am trying to use a union type for the props of a React component
type Props =
| {
type: "string"
value: string
}
| {
type: "number"
value: number
}
| {
type: "none"
}
class DynamicProps extends React.Component<Props> {
render() {
return null
}
}
// Ok
const string_jsx = <DynamicProps type="string" value="hello" />
// Error as expected, value should be a string
const string_jsx_bad = <DynamicProps type="string" value={5} />
// Ok
const number_jsx = <DynamicProps type="number" value={5} />
// Error as expcted value should be a number
const number_jsx_bad = <DynamicProps type="number" value="hello" />
// Error as expected, invalid isn't a property on any of the unioned types
const extra = <DynamicProps type="string" value="extra" invalid="what" />
// No error? There should be no value when type="none"
const none_jsx = <DynamicProps type="none" value="This should be an error?" />
// Ok, seems like value has become optional
const none2_jsx = <DynamicProps type="none" />
// Error as expected, value is not present. Value doesn't seem to be made optional all the time
const required = <DynamicProps type="string" />
It seems to partially work as depending on the type
prop the valid props will change. However, while extra properties that do not appear on any of the types in the union will be an error, it seems that a type that appears in at least one of the unioned types but does not belong based on the discriminant property will not be an error.
I'm not sure why this is the case. Is it an anti-pattern to be using union types as the props for react components?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…