为什么窄化在 React 组件函数中不能正常工作?

问题描述 投票:0回答:1

我在反应组件中遇到了联合问题。下面的代码示例似乎已损坏,但我很困惑为什么会发生这种行为。

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

javascript reactjs typescript
1个回答
1
投票

您需要一个文字类型来区分

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
    }
};

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.