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
相关产品推荐
相关产品推荐

