React组件TypeScript interface定义:如何声明未指定的Rest Props?
在TypeScript React组件中声明剩余Props的类型
针对你的场景,分两种常见情况来定义组件的Props接口:
1. 明确知道传递给子组件的Props类型(推荐)
如果RandomComp有自己的Props类型定义,直接让FuncComponentProps继承该类型即可,TypeScript会自动处理剩余属性的类型推断:
import React from 'react'; // 假设RandomComp的Props类型 interface RandomCompProps { className?: string; onClick?: () => void; // 其他RandomComp支持的属性 } interface FuncComponentProps extends RandomCompProps { icon: string; // 组件自身的特定属性 } function FuncComponent({ icon, ...restProps }: FuncComponentProps) { // restProps自动匹配RandomCompProps的类型 return <RandomComp {...restProps} />; }
这种方式类型最安全,能严格校验传递的额外属性是否符合子组件要求。
2. 无特定Props,需接受任意额外属性
如果完全不确定要传递哪些额外属性,或者需要兼容任意键值对,可以使用索引签名来定义:
import React from 'react'; interface FuncComponentProps { icon: string; // 允许任意字符串键,值类型用unknown(比any更安全,需要显式类型转换) [key: string]: unknown; } function FuncComponent({ icon, ...restProps }: FuncComponentProps) { return <RandomComp {...restProps} />; }
如果是要兼容HTML元素的原生属性(比如子组件是div、button等DOM元素的包装),可以直接继承React内置的HTML属性类型:
import React from 'react'; // 假设RandomComp是基于div的组件,继承div的所有属性 interface FuncComponentProps extends React.HTMLAttributes<HTMLDivElement> { icon: string; } function FuncComponent({ icon, ...restProps }: FuncComponentProps) { return <RandomComp {...restProps} />; }
关键说明
当你在组件参数中解构{icon, ...restProps}时,TypeScript会自动将restProps的类型推断为FuncComponentProps中除icon以外的所有属性类型,只要接口定义正确,剩余属性的类型会被自动处理。
内容的提问来源于stack exchange,提问作者Crepkey
相关产品推荐
相关产品推荐

