【发布时间】:2019-04-30 14:21:11
【问题描述】:
我将 React 组件作为变量传递,并尝试使用正确的类型保护自己免受运行时错误的影响。问题是,当我需要从变量实例化组件时,prop-types 感觉是“颠倒的”。下面的 sn -p 会更好的说明问题。
还有我找到的解决方案 - 用功能组件包装组件,它只是传递道具
interface IBaseStore {
prop: number;
}
interface IExtendedStore extends IBaseStore {
extraProp: number;
}
type ComponentProps<StoreT> = {
store: StoreT;
};
const BaseComponent = (props: ComponentProps<IBaseStore>) => <div>{props.store.prop}</div>;
const ExtendedComponent = (props: ComponentProps<IExtendedStore>) => <div>{props.store.extraProp}</div>;
type ConfigProps<StoreT> = {
additionalLayer: ComponentType<ComponentProps<StoreT>>;
};
const tableConfigCorrect1: ConfigProps<IBaseStore> = {
additionalLayer: BaseComponent,
};
const tableConfigCorrect2: ConfigProps<IExtendedStore> = {
additionalLayer: BaseComponent,
};
const tableConfigWrongType1: ConfigProps<IBaseStore> = {
additionalLayer: ExtendedComponent, // No TS error
};
const runtimeError = <tableConfigWrongType1.additionalLayer store={{ prop: 5 }}/>;
// Solution:
const tableConfigWrongType2: ConfigProps<IBaseStore> = {
additionalLayer: props => <ExtendedComponent {...props}/>, // TS error, not compiled
};
感觉像是“倒置”子类型的常见 OOP 问题,我正在寻找一些模式或 TS 类型以更简洁的方式解决它
【问题讨论】:
标签: reactjs typescript typescript-typings