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

React项目TypeScript误报:属性name不存在于IntrinsicAttributes类型

React项目TypeScript报错:name属性不存在于IntrinsicAttributes类型

在React+TypeScript项目中使用自定义组件PatchField时,触发以下TypeScript错误:

S2322: Type { name: string; render: ({ value, setValue }: { value: any; setValue: any; }) => Element; } is not assignable to type IntrinsicAttributes
Property name does not exist on type IntrinsicAttributes

报错场景代码

<PatchField
    name="name"
    render={({ value, setValue }) => (
        <Input
            placeholder="Enter a name"
            value={(value ?? "").toString()}
            onChange={getHandleTextValueChange(setValue)}
            maxLength={TITLE_FIELD_MAX_LENGTH}
            showInputLength={false}
            variant="ghost"
            size="large"
        />
    )}
/>

矛盾点

PatchField的Props接口明确定义了name字段:

interface PatchFieldProps {
    name: string;
    render: (args: RenderArgs) => ReactNode;
}

通过ComponentProps<typeof PatchField>查询、IDE跳转定义或悬浮提示均可验证这一点,但运行tsc --noEmit仍会触发报错,使用的TypeScript版本为v4.9.5,并非IDE专属问题。

PatchField组件实现代码

import { memo, ReactNode, useMemo } from "react"
import { useField, useFormikContext } from "formik"
import { FieldValue } from "../../typings.ts"

interface PatchFieldProps {
    name: string
    render: (args: RenderArgs) => ReactNode
}

export const PatchField = memo((props: PatchFieldProps) => {
    const { name, render } = props
    const { submitForm } = useFormikContext()
    const [fieldProps, _meta, helpers] = useField<FieldValue>(name)

    return useMemo(() => {
        const setValue = (value: FieldValue) => {
            void helpers.setValue(value, false)
        }
        return render({
            value: fieldProps.value,
            setValue,
            patchValue: () => {
                void submitForm()
            },
        })
    }, [submitForm, helpers, fieldProps.value, render])
})

问题原因与解决方案

原因

React的memo函数在未显式指定泛型参数时,TypeScript无法正确推断包裹组件的Props类型,会将组件误判为仅支持HTML元素默认属性(即IntrinsicAttributes),从而无法识别自定义的name、render等Props。

解决方案

给memo显式传入组件Props类型作为泛型参数,帮助TypeScript正确推导:

// 修改组件定义,指定memo的泛型参数
export const PatchField = memo<PatchFieldProps>((props) => {
    // 原有实现代码保持不变
})

或者先定义组件函数再包裹memo,TypeScript会自动推断泛型参数:

const PatchFieldComponent = (props: PatchFieldProps) => {
    // 原有实现代码保持不变
}

export const PatchField = memo(PatchFieldComponent)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:57:20