reactjs - Typescript 无法正确推断 HOC 中的 this.props

标签 reactjs typescript

考虑以下虚拟 HOC

interface SelectOption {
  value: string;
  label: string;
}

interface HOCProps {
  value: string | SelectOption;
}

const testHOC = <P extends HOCProps>(Component: React.ComponentType<P>): React.ComponentType<P> =>
  class Wrapper extends React.Component<P> {
    constructor(props: P) {
      super(props);
      console.log(this.props.value);
      console.log(props.value);
  }

  render() {
    return <Component {...this.props} />;
  }
};

Typescript 按预期识别 props.value:

(property) HOCProps.value: string | SelectOption

但是在 this.props.value 中我得到了不同的结果:

(property) value: P["value"]

如何修复类型注释,以便 typescript 正确推断 this.props
附: codesanbox link to the code in question

最佳答案

您看到 this.props 之间差异的原因和 props在你的构造函数中,它们实际上是不同的类型。

props键入为 P在构造函数中,同时 this.propsReact.Component 中定义作为props: Readonly<P> & Readonly<{ children?: ReactNode }>;

Readonly在 typescript 库中定义为 mapped type ,因此您在悬停时会看到 P["value"]因为这是从映射类型中提取的。

typescript 维护者已提出此问题,multiple times一直fixed .

但由于某种原因,向您显示类型的引擎可能无法解析这些映射类型。

使用 JetBrains IntelliJ,类型解析正确,而在 codesandbox 中我只看到未解析的类型 P["value"]它指的是映射类型...

example screenshot

这个问题也可以在这个最小的例子中看到:

interface Base {
  value: string | number;
}

const test = <T extends Base>(a: T, b: Readonly<T>) => {
  console.log(a.value, b.value);
}

根据维护者的说法,这是 typescript 的一个已知设计限制:https://github.com/microsoft/TypeScript/issues/32932#issuecomment-522353713

关于reactjs - Typescript 无法正确推断 HOC 中的 this.props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57479489/

相关文章:

Angular 6 : Local workspace file ('angular.json' ) could not be found

javascript - 如何将 Material-UI Autocomplete 与 react-virtualized 一起使用?

javascript - 子组件值到父组件显示React Native

javascript - 如何将组件的结果呈现为卡片

javascript - 在 Typescript 中向基类添加扩展

typescript - 如何使用 Jest 模拟模拟模块的方法?

reactjs - 在自定义抽屉上设置 activeTintColor

javascript - 通过外部交互更新 React 组件状态

Typescript addEventListener 设置事件类型

javascript - 将 Javascript 成员变量转换为 Typescript 成员变量