Reactjs 导航项目的条件类型

Reactjs 导航项目的条件类型,reactjs,typescript,next.js,Reactjs,Typescript,Next.js,我想定义我的界面,这样当你给出一个导航项目的导航时,你可以选择给childs一个下拉列表。当给定childs属性时,我希望强制navigationItem的icon属性。 如果未提供childs属性,则不应提供icon属性 你知道我怎样才能做到吗 这是我当前的界面 interface dropdown { name: string; href: string; icon: IconDefinition; } interface navigationItem { name: str

我想定义我的界面,这样当你给出一个导航项目的导航时,你可以选择给childs一个下拉列表。当给定childs属性时,我希望强制navigationItem的icon属性。 如果未提供childs属性,则不应提供icon属性

你知道我怎样才能做到吗

这是我当前的界面

interface dropdown {
  name: string;
  href: string;
  icon: IconDefinition;
}
interface navigationItem {
  name: string;
  href: string;
  icon: IconDefinition; // only needed if the childs is given
  childs?: dropdown[];
}

您应该能够使用两个不同的接口来实现这一点

type Type3 = Type1 | Type2;
有一个

interface Type1 {
    name: string;
    href: string;
    childs: never;
}
第二个是

interface Type2 {
    name: string;
    href: string;
    childs: dropdown[];
    icon: IconDefinition;
}
然后您可以使用这样的条件语句来使用这两种类型

value: Type1 | Type2
const a: Type3;
这样做的原因是,当您将
图标:never
添加到
类型1
时,您只能有
名称
href

因此,如果有人添加了
childs
键,那么类型就变成了
Type2
,这也需要给出
图标

因此,如果
const a:Type1 | Type2={name:'',href:'',childs:[]},它抛出

Type '{ name: string; href: string; childs: []; }' is not assignable to type 'Type1 | Type2'.
Property 'icon' is missing in type '{ name: string; href: string; childs: dropdown[]; }' but required in type 'Type2'.
如果您想改用单一类型,请定义如下的新类型

type Type3 = Type1 | Type2;
然后像这样使用它

value: Type1 | Type2
const a: Type3;

嗨,不是因为我想设置图标的类型,这取决于是否提供了可选的child。您的东西只为一个项目提供可选类型,而不取决于问题中的另一个项目,当您有
childs
在场时,您似乎只需要传递
icon
,否则两者都可能缺席。这不是你需要的吗?如果没有,请更新问题。我是一个很困惑的人。对不起,更新了question@MaximeGh莱尔已经更新了我的答案。thx,我明白你的意思,但是不说value:type1 | type2难道不可能吗?我想保持它的值:type2,这是自动知道孩子们是给定的,所以图标也应该