无法使用mobx-react-lite定义观察者proptypes。
我已经尝试将泛型用于观察者函数,但它提供了一个错误。
做这样的事情很好:
import { observer } from 'mobx-react-lite';
type PassedProps = {
foo: string,
num: number
}
const Element = (props: PassedProps) => null;
observer<PassedProps>(Element)
但是在一个更复杂的例子中:
import { observer } from 'mobx-react-lite';
import { StoreContext } from 'index';
export function connect<MappedProps, PassedProps> (
mapStoreToProps: (store: any, ownProps:PassedProps) => MappedProps,
UIComponent: React.FunctionComponent<MappedProps & PassedProps>
) {
const WrappedComponent = (props: PassedProps) => {
const store = React.useContext(StoreContext);
const mapped = mapStoreToProps(store, props);
return UIComponent({...mapped, ...props});
}
return observer<PassedProps>(WrappedComponent);
}
它错误:
Type 'PassedProps' does not satisfy the constraint 'object'
当然,我现在明白了。我必须定义泛型类型约束:
export function connect<MappedProps extends object, PassedProps extends object> (
mapStoreToProps: (store: any, ownProps:PassedProps) => MappedProps,
UIComponent: React.FunctionComponent<MappedProps & PassedProps>
) {
const WrappedComponent = (props: PassedProps) => {
const store = React.useContext(StoreContext);
const mapped = mapStoreToProps(store, props);
return UIComponent({...mapped, ...props});
}
return observer<PassedProps>(WrappedComponent);
}