网站搜索

reactjs - 我想根据 Props 值的类型显示 div 标签


当值的类型是 { query: string; isSelect: boolean } 且 isSelect 为 true 时,我想显示选中。

错误 属性 'isSelect' 在类型 '{ query: string; isSelect: boolean; } | { query: string; }' 中不存在。 属性 'isSelect' 在类型 '{ query: string; }' 中不存在。

interface Props {
  name: string;
  onClick: () => void;
  values: { query: string; isSelect: boolean } | { query: string };
}

export const Category: React.VoidFunctionComponent<Props> = ({
  return (
    <div>
      <div>
        <p>{name}</p>
        <button onClick={onClick}></button>
      </div>
      <div>
        {values.query}
      </div>
      {values.isSelect &&
      <div>
        selected
     </div>
              }
    </div>
  );
};

答案#1

你声明值的类型为:

{ query: string; isSelect: boolean } | { query: string };

这意味着该属性可能存在,也可能不存在。而 Typescript 只会允许你访问以某种方式声明过的属性。

由于 { query: string } 上不存在 isSelect,所以你无法访问该属性。

但是,如果您将属性声明为可选的,那么您就是在说它可以省略,但仍然允许访问它:

interface Props {
  name: string;
  onClick: () => void;
  values: { query: string; isSelect?: boolean };
  //                               ^ this here makes the property optional
}

那么它就按你预期的那样工作。

看看这个没有类型错误的操场。


或者,如果你不想更改类型,你可以使用 in 运算符来检查属性是否存在。

{'isSelect' in values && values.isSelect &&
  <div>
    selected
  </div>
}

这告诉 TypeScript 你在运行时测试了该值属于联合类型的哪一个分支,然后一旦你证明它存在,就可以访问该属性。这被称为类型缩小

查看游乐场