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

React组件传入ItemProps数组时类型不兼容报错求助

类型不兼容错误原因解析

错误信息

Type '{ label: string; icon: string; badge: { type: string; }; } | { label: string; icon: string; badge?: undefined; }' is not assignable to type 'ItemProps'.
Type '{ label: string; icon: string; badge: { type: string; }; }' is not assignable to type 'ItemProps'.
The types of 'badge.type' are incompatible between these types.
Type 'string' is not assignable to type "indicator" | "info" | undefined'.

相关代码

import React from "react"

export interface BadgeProps {
  type?: "indicator" | "info"
}

export interface ItemProps {
  label?: string,
  icon?: string
  disabled?: boolean
  badge?: BadgeProps
}

export interface ItemsProps {
  items: ItemProps[]
}

const Items: React.FunctionComponent<ItemsProps> = ({ items }) => {
  return (
    <div>
      { String(items) }
    </div>
  )
}

const Test: React.FunctionComponent = () => {
  
  const items = [
    {
      label: "Home",
      icon: "MdHome",
      badge: {
        type: "indicator"
      }
    },
    {
      label: "Profile",
      icon: "MdPerson"
    },
    {
      label: "Settings",
      icon: "MdSettings"
    }
  ]

  return (
    <Items items={items}/>
  )
}

export default Test

错误原因

  • TypeScript对items数组做类型推断时,会把第一个元素里badge.type的类型默认推断为宽泛的string,而非你定义的"indicator" | "info"联合类型。
  • 当把这个数组传给要求ItemProps[]类型的Items组件时,TypeScript检测到string类型无法匹配BadgeProps中type的受限联合类型,因此抛出类型不兼容错误。
  • 核心问题是TypeScript对对象字面量的默认推断逻辑会采用更通用的类型,没有自动识别出你希望badge.type匹配预定义的枚举值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:30:57