我在反应组件中遇到了联合问题。下面的代码示例似乎已损坏,但我很困惑为什么会发生这种行为。
type Props =
| { value: string; onChange: (value: string) => void }
| {
value: Array<string>;
onChange: (value: Array<string>) => void;
};
const App = (props: Props) => {
const func = () => {
if (typeof props.value === 'string') {
const val = props.value; // works fine
const change = props.onChange; // still union - might contain both types of value
}
};
return <div></div>
};
如何修复该问题并在 onChange 回调中仅看到
(e: string) => void
?
您需要一个文字类型来区分
value
不是的并集。
type Props =
| { value: string; onChange: (value: string) => void, type: 'foo' }
| {
value: Array<string>;
onChange: (value: Array<string>) => void;
type: 'bar',
};
const App = (props: Props) => {
if (props.type === 'foo') {
const val = props.value; // string
const change = props.onChange; // onChange: (value: string) => void
}
};