我正在努力了解如何验证两个道具是否存在。
换句话说,它们都是可选的,但如果其中一个存在,另一个也必须存在。
我不太明白条件类型在这种情况下如何工作,在我见过的所有示例中,条件是该类是否扩展另一个类,那么这里如何工作呢?
interface DateInputProps {
onDateChange: (date: Date) => void;
date: any;
}
interface DateInputPropsNull {}
type SelectiveProps<T> = T extends _what?_
? DateInputPropsNull
: DateInputProps;
class DateInput extends React.Component<
SelectiveProps<_what?_>,
DateInputState
> {
render() {
const {
date = this.state.date,
onDateChange = (date: any) => this.setState({ date })
} = this.props;
...
}
}
Run Code Online (Sandbox Code Playgroud)
然后我希望能够做到:
<DateInput /> //No type error
<DateInput date="2011-01-05" onDateChange={(date)=> console.log(date)}/> //No type error
<DateInput date="2011-01-05" /> //Error - onDateChange is required
Run Code Online (Sandbox Code Playgroud)