开启TypeScript严格模式后出现类型缺失属性错误求助
解决TypeScript严格模式下的组件类型不兼容问题
问题背景
代码在TypeScript非严格模式下运行正常,但开启严格模式后出现类型错误:
Type 'Common' is missing the following properties from type 'Employee': name, position, department.
原代码示例
import { FC } from 'react'; interface Common { id: string; } // ChildComponent.tsx type argType = Common | (Common & Record<string, unknown>); interface ChildComponentProps { renderFun: (item: argType) => React.ReactNode; } const ChildComponent: FC<ChildComponentProps> = (props) => { // 组件逻辑 return null; }; // ParentComponent.tsx interface Employee extends Common { name: string; position: string; department: string; } const ParentComponent = () => { return ( <> <ChildComponent renderFun={(item: Employee) => <>render something...</>} // 此处报错 /> </> ); };
问题原因
严格模式下TypeScript会严格检查函数参数的逆变兼容性:ChildComponentProps要求renderFun能接受所有argType类型的参数(包括基础的Common),但父组件传入的函数仅能处理更具体的Employee类型,无法兼容宽泛的Common类型,因此触发类型错误。
解决方案:使用泛型组件
将ChildComponent改为泛型组件,让其接收一个继承自Common的类型参数,动态适配不同的子类型:
修改后的ChildComponent
import { FC } from 'react'; interface Common { id: string; } // ChildComponent.tsx interface ChildComponentProps<T extends Common> { renderFun: (item: T) => React.ReactNode; } const ChildComponent = <T extends Common>(props: ChildComponentProps<T>) => { // 组件逻辑 return null; };
父组件使用方式
// ParentComponent.tsx interface Employee extends Common { name: string; position: string; department: string; } const ParentComponent = () => { return ( <> {/* 自动推导泛型类型 */} <ChildComponent renderFun={(item: Employee) => <>render something...</>} /> {/* 或显式指定泛型 */} {/* <ChildComponent<Employee> renderFun={(item) => <>render something...</>} /> */} </> ); };
方案说明
泛型让ChildComponent可以灵活适配所有继承自Common的类型,renderFun的参数类型会被约束为传入的具体子类型,既满足严格模式下的类型检查要求,又保留了组件的复用性,支持多种业务场景的不同参数类型。
内容的提问来源于stack exchange,提问作者Dimitriy
相关产品推荐
相关产品推荐

