【问题标题】:conditional types for nav item导航项的条件类型
【发布时间】:2021-05-14 12:12:53
【问题描述】:

我想定义我的界面,以便当您提供作为导航项的导航时,您可以选择为下拉菜单提供子项。当给定 childs 属性时,我想强制执行 navigationItem 的 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[];
}

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

    您应该能够使用两个不同的接口来做到这一点。

    有一个

    interface Type1 {
        name: string;
        href: string;
        childs: never;
    }
    

    第二个是

    interface Type2 {
        name: string;
        href: string;
        childs: dropdown[];
        icon: IconDefinition;
    }
    

    然后你可以使用这样的条件来使用这两种类型

    value: Type1 | Type2
    

    为什么会这样,当您将icon: never 添加到Type1 时,您只能拥有namehref 键。

    因此,如果有人添加了 childs 键,那么类型将变为 Type2,这也需要提供 icon

    所以,如果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;
    

    那就这样用吧

    const a: Type3;
    

    【讨论】:

    • 嗨,不是真的因为我想设置图标的类型取决于或是否给出了可选的子项。你的东西只为一项提供可选类型,而不依赖于另一项
    • 从问题来看,当你有childs 存在时,你似乎只需要传递icon,否则两者都可能不存在。这不是你需要的吗?如果没有,请更新问题。我很困惑。
    • @MaximeGhéraille 已更新我的答案。看看吧。
    • thx,我明白你的意思,但不说价值就不可能:type1 |类型2?我想保留它的值:type2 并且自动知道给定了孩子,所以图标也应该
    • @MaximeGhérille我已经更新了我的答案。看看这个。您可以使用type Type3 = Type1 | Type2; 创建一个新类型,然后使用新类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2017-08-20
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    相关资源
    最近更新 更多