【问题标题】:Recompose + TypeScript - type error on additional propsRecompose + TypeScript - 附加道具上的类型错误
【发布时间】:2018-12-16 16:44:12
【问题描述】:

我目前正在尝试使用 Recompose 在项目中实现 TypeScript 以增强以下组件:

import { compose } from 'recompose';

// This is my Base Component that is reused throughout the App.
interface BaseOuterProps {
 value: any;
}

const StatelessBaseComponent = () => <div />;
const BaseComponent = compose<any, BaseOuterProps>(...)(StatelessBaseComponent);

// This is one of the higher components that needs to use the Base Component by enhancing it.

interface HigherInnerProps {
 value: any;
 something: any;
}

const HigherComponent = compose<HigherInnerProps, any>(...)(BaseComponent);

我遇到的问题是,当 HigherComponent 类型 (HigherInnerProps) 的 props 比 BaseComponent 类型 (BaseOuterProps) 多时,我收到以下错误:

Type 'ComponentClass' 没有为 签名 '(props: HigherInnerProps & { children?: ReactNode; }, 上下文?:任何):ReactElement |空'

我试图让 BaseOuterProps 更灵活:

interface BaseOuterProps {
 value: any;
 [key: string]: any | void | null;
}

没有运气。

类型由@types/react 和@types/recompose 提供。

关于如何保留类型链接并满足错误要求的任何想法?

【问题讨论】:

    标签: reactjs typescript recompose


    【解决方案1】:

    如果你尝试怎么办

    import { compose } from 'recompose';
    
    // This is my Base Component that is reused throughout the App.
    interface BaseOuterProps {
      value: any;
    }
    
    const StatelessBaseComponent = () => <div />;
    const BaseComponent = compose<BaseOuterProps, any>(...) 
      (StatelessBaseComponent);
    
    // This is one of the higher components that needs to use the Base Component by enhancing it.
    
    interface HigherInnerProps {
      value: any;
      something: any;
    }
    
    const HigherComponent = compose<BaseOuterProps & HigherInnerProps, HigherInnerProps>(...)(BaseComponent);
    

    【讨论】:

    • 感谢您的回复,并对延误表示抱歉。这肯定会起作用,但这意味着 BaseComponent -> HigherComponent 之间的链接不会被保留。我希望它还能将导出的 BaseComponent 类型与 HigherComponent 预期目标类型进行比较。
    • 抱歉,我有点搞不懂你的意思是什么?
    • 假设我的 BaseOuterProps 是 { value: string; } 而我的 HigherInnerProps 是 { value: integer; },我希望类型检查器可以通过某种方式告诉我:“您正在尝试将 { value: string; } 插入 { value: integer; }。这是错误的。”
    【解决方案2】:

    1- 在根目录下创建文件夹@types

    2-创建文件夹recompose并在其中撰写

    ├── src
    ├── @types
    │   └── recompose
    │       └── compose
    │           └── index.d.ts
    └── tsconfig.json
    

    3- 在 tsconfig.json 中添加以下内容

    {
      ...
      "compilerOptions": {
        ...
        "typeRoots": ["./@types"],
        ...
      },
      ...
    }
    

    4- 在 index.d.ts 中添加以下行

    declare module 'recompose/compose';
    

    【讨论】:

      猜你喜欢
      • 2018-12-09
      • 2019-01-07
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 2021-06-12
      • 2021-01-24
      相关资源
      最近更新 更多