Reputation: 73988
I would like to know if it is possible to set two properties as optional depending on another property in TypeScript, example:
If message
is undefined
I want a
and b
to be required,
If message
is not undefined
I want a
and b
to be optional.
How to enforce this condition?
type Props = Readonly<{
message?: React.ReactNode
a: React.ReactNode
b: React.ReactNode
}>
const Component = ({ message, a, b}: Props) => <div >
Upvotes: 2
Views: 453
Reputation: 250316
You can use a union type to achieve this effect:
type Props = Readonly<{
message?: undefined
a: string
b: string
} | {
message: string
a?: string
b?: string
}>
const Component = ({ message, a, b}: Props) => <div />;
let c = <Component message="" /> //ok
let c2 = <Component a="" b="" /> //ok
let c3 = <Component message="" b="" /> //ok
let c4 = <Component /> //error as expected
Upvotes: 4