【问题标题】:Type annotation for subclass factory子类工厂的类型注释
【发布时间】:2018-04-08 00:54:11
【问题描述】:

我最近开始将我公司的一个项目的代码库迁移到 TypeScript,我在为这段代码添加类型注释时遇到了困难:

function factory( Base ) {
  return class Extended extends Base {
    ...
  }
}

const Extended = factory( React.Component );
const PureExtended = factory( React.PureComponent );

我试图用 TypeScript 来描述:

  • 工厂只接受从 React.Component 类继承的类。
  • 工厂返回继承自 React.Component 类的类。

我尝试了什么:

function factory( Base: React.Component<P, S> ): React.Component<P, S> {
  return class Extended extends Base {
    ...
  }
}

const Extended = factory( React.Component );
const PureExtended = factory( React.PureComponent );

这在类型检查上非常失败。

我正在使用:

  • TypeScript 2.5.2
  • Visual Studio 代码 1.16.1
  • @types/react 16.0.14

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    如您在答案中链接到的文章所示,您需要使 mixin 工作是 Constructor 类型。或者,您可以通过向Constructor 提供特定类型来限制可以扩展的类。

    type Constructor<T> = new(...args: any[]) => T;
    
    function factory<T extends Constructor<React.Component>> ( Base: T ) {
      return class Extended extends Base {
        /* Extended implementation */
      };
    }
    
    export const Extended = factory( React.Component );
    export const PureExtended = factory( React.PureComponent );
    

    【讨论】:

      【解决方案2】:

      看来我设法让它与这个一起工作:

      type RCConstructor<P, S> = new(...args: any[]) => React.Component<P, S>;
      
      function factory<T extends RCConstructor<{}, {}>> ( Base: T ) {
        return class Extended extends Base {
          /* Extended implementation */
        };
      }
      
      export const Extended = factory( React.Component );
      export const PureExtended = factory( React.PureComponent );
      

      解决方案来自https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html。从文档中可以看出这里发生了什么。现在真正的问题是“为什么https://www.typescriptlang.org/docs/handbook/mixins.html 不涉及这个?”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多