reactjs - React、Typescript、条件属性

标签 reactjs typescript

我有这种类型:

export type InfoItemProps = (
  | { inputType: 'dropdown-menu'; options: string[] }
  | { inputType: 'text' }
  | { inputType: 'date' }
  | { inputType: 'text-aria' }
  | { inputType: 'phone-number' }
) & {
  name: string;
  labelText: string;
  value: string;
  editValue: string;
  editMode: boolean;
  onEditValueChange: (inputName: string, value: string) => void;
};

但每当我尝试访问选项时,它都会提示:

Property 'options' does not exist on type 
'{ inputType: "text"; } & { name: string; labelText: string; value: string;
 editValue: string; editMode: boolean; onEditValueChange: (inputName: string, value: string) => void; }'.

这是怎么回事?如何解决?

最佳答案

您应该检查 inputType === 'dropdown-menu' 是否:

export type InfoItemProps = (
  | { inputType: 'dropdown-menu'; options: string[] }
  | { inputType: 'text' }
  | { inputType: 'date' }
  | { inputType: 'text-aria' }
  | { inputType: 'phone-number' }
) & {
  name: string;
  labelText: string;
  value: string;
  editValue: string;
  editMode: boolean;
  onEditValueChange: (inputName: string, value: string) => void;
};

declare var obj: InfoItemProps;

if (obj.inputType === 'dropdown-menu') {
  obj.options // ok
}

关于reactjs - React、Typescript、条件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68635582/

相关文章:

reactjs - 在 React Native 中本地化为 LTR 时使用 RTL 方向

reactjs - 发送到我的服务器时,“使用Google登录” JWT无效

reactjs - 在 componentDidMount 内部的回调中设置状态

AngularJS 2 a Promise resolve 在 feching 时丢失类标识

typescript - Typescript 中是否需要访问器?

typescript - Function 接口(interface)是否缺少 new() 签名?

angular - 如何将 CSS 类应用于 AngularDart 中的另一个组件?

reactjs - Draft.js (react-draft-wysiwyg) : text update from the outside of the Editor component does not work

reactjs - 将错误响应拦截器放在 redux-axios-middleware 上

javascript - for 循环,迭代之间有 sleep