Skip to content

Instantly share code, notes, and snippets.

@erwinv
Created March 27, 2022 09:34
Show Gist options
  • Save erwinv/ab07745688847822f06e86cfa20e8722 to your computer and use it in GitHub Desktop.
Save erwinv/ab07745688847822f06e86cfa20e8722 to your computer and use it in GitHub Desktop.
Required/optional props depending on another prop/flag
interface CommonProps {
a: number
b: string
}
interface EnabledProps {
onChangeFn: (newVal: string) => void
}
type ConditionalProps =
| ({ disabled: true } & Partial<EnabledProps>)
| ({ disabled?: false} & Required<EnabledProps>)
type Props = CommonProps & ConditionalProps
const props1: Props = {
a: 1,
b: 'foo',
onChangeFn: () => {}
}
// Property 'onChangeFn' is missing in type '{ a: number; b: string; }' but required in type 'Required<EnabledProps>'
const props2: Props = {
a: 1,
b: 'foo',
}
const props3: Props = {
a: 1,
b: 'foo',
disabled: true,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment