类型“string”不可分配给类型“IconType”

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

我创建了这些类型

type IconType = {
    ico: "dashboard" | "program" | "score" | "record";
};

type NavigationRoute = {
    label: string;
    href: string;
    ico: IconType;
};

当我在此数组中实现 NavigationRoute 时,收到“类型‘string’不可分配给类型‘IconType’”:

const navigationRoutes: NavigationRoute[] = [
    {
        label: "Panel de control",
        href: "/panel",
        ico: "dashboard"
    },
    {
        label: "Items de puntuación",
        href: "/puntuacion",
        ico: "score"
    },
    {
        label: "Orden de salida",
        href: "/programa",
        ico: "program"
    }
];

ico 变量似乎是这里的问题。有人可以解释一下吗?

我将字符串添加到联合定义中,但它仍然不起作用。

type IconType = { ico: string | "dashboard" | "program" | "score" | "record"; };

我用代码创建了这个playground

typescript
1个回答
1
投票

您只需在 IconType 类型定义中添加额外的大括号即可。

这就是您要找的:

type IconType = "dashboard" | "score" | "program";

这是你需要别人为你指出的愚蠢错误之一:)

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