首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为props定义mobx-react-lite观察器泛型

为props定义mobx-react-lite观察器泛型
EN

Stack Overflow用户
提问于 2019-04-12 22:50:35
回答 1查看 343关注 0票数 0

无法使用mobx-react-lite定义观察者属性类型。

我尝试使用观察者函数的泛型,但它提供了一个错误。

做这样的事情是可以的:

代码语言:javascript
复制
import { observer } from 'mobx-react-lite';

type PassedProps = {
  foo: string,
  num: number
}
const Element = (props: PassedProps) => null;
observer<PassedProps>(Element)

但在一个更复杂的例子中:

代码语言:javascript
复制
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错误:

代码语言:javascript
复制
Type 'PassedProps' does not satisfy the constraint 'object'
EN

回答 1

Stack Overflow用户

发布于 2019-04-12 22:52:47

当然,我现在就想明白了。我必须定义泛型类型约束:

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55654297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档