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

React自定义Typography组件出现TypeScript错误求助

React Typography组件的TypeScript错误解决

我为React应用开发了一个基础的Typography组件,但遇到了TypeScript错误,以下是组件代码及报错信息,求分析解决:

Typography组件代码

import clsx from 'clsx';

const variants = {
    h1: 'h1',
    h2: 'h2',
    h3: 'h2',
    h4: 'h2',
    h5: 'h2',
    h6: 'h2',
    subheading1: 'h6',
    subheading2: 'h6',
    body1: 'p',
    body2: 'p',
    link: 'p',
};

const typographyVariants = {
    h1: 'text-6xl',
    h2: 'text-5xl',
    h3: 'text-4xl',
    h4: 'text-3xl',
    h5: 'text-2xl',
    h6: 'text-1xl',
    subheading1: 'text-1xl font-bold',
    subheading2: 'text-1xl font-semibold',
    body1: 'text-base',
    body2: 'text-base font-bold',
    link: 'text-xs text-primaryViolet uppercase underline font-bold',
};

export type TypographyProps = {
    variant?: keyof typeof variants;
    className?: string;
    children: React.ReactNode | string;
};

export const Typography = ({ variant = 'body1', className, children }: TypographyProps) => {
    const Component = variants[variant];
    const typographyStyles = typographyVariants[variant];

    return (
        <Component className={clsx('font-sans', typographyStyles, className)}>{children}</Component>
    );
};

TypeScript错误信息

返回语句中的<Component>部分出现如下错误:

Type '{ children: ReactNode; className: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'children' does not exist on type 'IntrinsicAttributes'.ts(2322)

问题原因与解决方法

原因

TypeScript默认会把variants对象的属性值推断为string类型,而非具体的HTML元素标签字面量(比如'h1'、'p')。这导致TypeScript无法识别Component是可接收children、className等props的React元素,因此抛出props不匹配的错误。

解决方式

方式一:用as const断言保留字面量类型

修改variants定义,添加as const让TypeScript将每个属性值推断为具体字面量类型:

const variants = {
    h1: 'h1',
    h2: 'h2',
    h3: 'h2',
    h4: 'h2',
    h5: 'h2',
    h6: 'h2',
    subheading1: 'h6',
    subheading2: 'h6',
    body1: 'p',
    body2: 'p',
    link: 'p',
} as const;
方式二:显式指定类型标注

给variants指定类型,明确其值为React支持的HTML元素标签名(keyof JSX.IntrinsicElements):

const variants: Record<keyof typeof typographyVariants, keyof JSX.IntrinsicElements> = {
    h1: 'h1',
    h2: 'h2',
    h3: 'h2',
    h4: 'h2',
    h5: 'h2',
    h6: 'h2',
    subheading1: 'h6',
    subheading2: 'h6',
    body1: 'p',
    body2: 'p',
    link: 'p',
};

两种方式都能让TypeScript正确识别Component是合法的React HTML元素,从而允许传递children和className等props,解决报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:54:27