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

TypeScript错误ts(18048)排查:BoxerCard类型不匹配问题

TypeScript错误ts(18048)解决:BoxerCard类型不兼容问题

问题核心

BoxerCard组件触发ts(18048)错误,根源是类型不匹配:

  • Types.tsx中BoxerCardInterface定义age为number类型
  • BoxerData.tsx里的age字段是带单位的字符串(如'19 years old'或'19'),导致传入组件时类型不符

解决方案

方案1:修改接口适配数据源

如果业务需要保留age的完整字符串(比如渲染时显示带单位),直接调整接口类型:

修改Types.tsx:

import React from "react";

export interface BoxerCardInterface {
  name: string;
  imgUrl: any;
  age: string; // 将number改为string,匹配数据源类型
  status: string;
}

export interface CoachCardInterface {
  name: string;
  imgUrl: any;
  title: string;
}

修改后组件可直接接收字符串类型的age,无需额外处理。

方案2:转换数据类型适配接口

如果业务要求age必须是number类型,在渲染时提取字符串中的数字并转换:

修改Boxers.tsx的渲染逻辑:

import React from "react";
import { BoxerCard } from "../components/BoxerCards";
import BoxerData from "../data/BoxerData";
import { BoxerCardInterface } from "../data/Types";

export function Boxers() 
{
    return (
    <div className="flex flex-col md:flex-rows items-center justify-center">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {BoxerData.map(boxers => {
                // 从age字符串中提取数字,转为number类型
                const parsedAge = parseInt(boxers.age.match(/\d+/)?.[0] || '0', 10);
                return (
                    <BoxerCard
                        imgUrl={boxers.imgUrl}
                        name={boxers.name}
                        age={parsedAge}
                        status={boxers.status}
                    />
                )
            })}
        </div>
    </div>
    )
}

额外优化:给数据源添加类型约束,避免后续新增数据出错,修改BoxerData.tsx:

import React from "react";
import { BoxerCardInterface } from "./Types";

// 定义原始数据类型,age为string,后续转换为接口要求的number
type RawBoxerData = Omit<BoxerCardInterface, 'age'> & { age: string };

export default [
    {
    name: 'Natalia Castaneda',
    imgUrl: '',
    age: '19',
    status: 'Open'
   }, 
   {
    name: 'Joel Sanchez',
    imgUrl: '',
    age: '19 years old',
    status: 'Open'
   }, 
   {
    name: 'Scott Mcfadden',
    imgUrl: '',
    age: '20 years old',
    status: 'Open'
   }, 
   {
    name: 'Augusta Grace',
    imgUrl: '',
    age: '26 years old',
    status: 'Novice'
   }, 
   {
    name: 'Alex Garcia',
    imgUrl: '',
    age: '19 years old',
    status: 'Novice'
   },
   {
    name: 'Mia Andre',
    imgUrl: '',
    age: '13 years old',
    status: 'Novice'
   },
    {
    name: 'Jocelyn Castaneda',
    imgUrl: '',
    age: '13 years old',
    status: 'Novice'
   }
] as RawBoxerData[];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:25:25