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

如何传递otherProps且不触发TypeScript接口错误?

解决TypeScript组件属性传递类型不匹配问题

问题出在IWrapperProps的类型定义上:你用了字符串索引签名[otherProps: string]: unknown,导致TypeScript认为解构后的otherProps里所有属性都是unknown类型,而DateTime组件需要明确的name(string类型)、description和value,类型不兼容所以报错。

要通过扩展语法实现属性传递,只需调整接口定义,让IWrapperProps包含DateTime所需的全部属性,同时保留自身的flag:

interface IDateTimeProps {
    name: string
    description: any
    value: any
}

// 让Wrapper的属性继承DateTime的属性,加上自己的flag
interface IWrapperProps extends IDateTimeProps {
    flag: any
    // 如果需要允许Wrapper接收额外非必填属性,保留下面的索引签名;不需要就删掉
    [extraProps: string]: unknown
}

const Wrapper = (props: Readonly<IWrapperProps>) => {
    const { flag, ...otherProps } = props
    return (
        <div>
            <DateTime {...otherProps} />
        </div>
    )
}

这样修改后,解构出来的otherProps类型会和IDateTimeProps完全匹配(如果保留索引签名,就是IDateTimeProps加上额外未知属性,只要DateTime组件允许接收额外属性就没问题),TypeScript不会再抛出属性缺失的错误。

如果DateTime组件不允许接收额外属性,直接删掉IWrapperProps里的索引签名即可,确保Wrapper只接收flag和DateTime所需的三个属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:01:17