如何解决React TypeScript中ComponentType属性接受缺失props的问题
问题原因
这个现象是TypeScript的函数类型兼容规则导致的:无参函数默认可以赋值给「要求接收指定参数」的函数类型,因为运行时向无参函数传参不会触发异常。React内置的ComponentType本质是函数组件和类组件类型的联合,因此也遵循该规则,所以你传递无props的NoProps组件时不会触发报错。
解决方案
你可以自定义一个严格版的组件类型工具,强制要求传入组件的props必须包含你指定的所有属性,排除空props的情况:
import { ComponentType } from 'react'; // 自定义严格组件类型工具 type StrictComponentType<RequiredProps extends {}> = // 提取传入组件的props类型 ComponentType<RequiredProps> extends infer T ? T extends ComponentType<infer ComponentProps> // 排除props为空对象的组件 ? {} extends ComponentProps ? never // 要求组件props必须包含所有必填属性 : RequiredProps extends ComponentProps ? T : never : never : never; type A = { foo: string; } // 替换原来的ComponentType为StrictComponentType type B = { Component: StrictComponentType<A>; } const Test = ({ Component }: B) => ( <Component foo="test" /> ); const NoProps = () => <div />; const CorrectProps = ({ foo }: A) => <div />; const IncorrectProps = ({ bar }: { bar: string }) => <div />; // 现在会报错,符合预期 const C = () => <Test Component={NoProps} />; // 无报错,符合预期 const D = () => <Test Component={CorrectProps} />; // 报错,符合预期 const E = () => <Test Component={IncorrectProps} />;
注意:如果你的组件没有显式定义props类型,TS会默认推导props为any,也会被该工具类型拦截,强制要求你显式声明组件props,进一步保证类型安全。
内容的提问来源于stack exchange,提问作者georges8899
相关产品推荐
相关产品推荐

