如何为带有额外variant属性的React组件指定正确的TypeScript类型
单个变体的修复方案
你遇到的报错原因是React.FC<Props>类型本身没有定义variant1这个额外属性,需要显式给组件定义包含挂载属性的复合类型:
import React from 'react'; type Props = { text: string }; // 定义变体组件的类型,和主组件复用相同入参 type VariantComp = React.FC<Props>; // 复合类型:本身是React组件,同时带variant1属性 type SampleCompType = React.FC<Props> & { variant1: VariantComp; }; // 先定义基础组件 const BaseComp: React.FC<Props> = ({text}) => <div>{text}</div>; // 挂载变体 BaseComp.variant1 = ({text}) => <div>{`variant1${text}`}</div>; // 导出时指定复合类型 export const SampleComponent = BaseComp as SampleCompType;
这种方案比直接用宽泛的类型断言更安全,TS会对组件和变体的入参做完整类型校验。
4个动态变体的处理方案
如果是规律命名的多个变体,可以用模板字面量+索引签名简化类型定义,不需要逐个声明属性:
import React from 'react'; type Props = { text: string }; type VariantComp = React.FC<Props>; // 模板字面量匹配variant1~variant4所有属性 type SampleCompType = React.FC<Props> & { [key in `variant${1|2|3|4}`]: VariantComp; }; const BaseComp: React.FC<Props> = ({text}) => <div>{text}</div>; // 挂载所有变体 BaseComp.variant1 = ({text}) => <div>{`variant1${text}`}</div>; BaseComp.variant2 = ({text}) => <div>{`variant2${text}`}</div>; BaseComp.variant3 = ({text}) => <div>{`variant3${text}`}</div>; BaseComp.variant4 = ({text}) => <div>{`variant4${text}`}</div>; export const SampleComponent = BaseComp as SampleCompType;
后续如果要新增变体,只需要在联合类型1|2|3|4中追加对应数字即可,维护成本极低。
内容的提问来源于stack exchange,提问作者Jason M
相关产品推荐
相关产品推荐

