无法使用mobx-react-lite定义观察者属性类型。
我尝试使用观察者函数的泛型,但它提供了一个错误。
做这样的事情是可以的:
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);
}It错误:
Type 'PassedProps' does not satisfy the constraint 'object'发布于 2019-04-12 22:52:47
当然,我现在就想明白了。我必须定义泛型类型约束:
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);
}https://stackoverflow.com/questions/55654297
复制相似问题