You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Type 'string'无法赋值给类型'IconType'问题求助

TypeScript类型错误:"string"无法赋值给"IconType"

问题场景

我定义了以下类型:

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

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

在实现NavigationRoute数组时,收到错误提示:Type 'string' is not assignable to type '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"
    }
];

我尝试修改IconType为包含string的联合类型,但仍然无效:

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

问题分析与解决方案

问题根源

IconType被定义为对象类型(包含ico属性的对象),但数组中直接给ico字段赋值了字符串值,TypeScript期望的是对象而非字符串,因此触发类型不匹配错误。

解决方案1:调整IconType为字符串字面量联合类型

如果你的需求是让ico直接存储指定的字符串值,无需嵌套对象,直接修改IconType的定义:

// 改为字符串字面量联合类型
type IconType = "dashboard" | "program" | "score" | "record";

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

此时数组中的ico: "dashboard"就能正确匹配类型。

解决方案2:保持对象类型,修正数组赋值格式

如果必须保留IconType的对象结构,那么在数组中给ico赋值时,需要传入包含ico属性的对象:

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

内容的提问来源于stack exchange,提问作者mahestro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:15:16