【问题标题】:Typescript class enhancer and static methodsTypescript 类增强器和静态方法
【发布时间】:2019-08-15 12:45:17
【问题描述】:

对于 NextJS 应用程序,我想创建一个 App (_app.tsx) 类增强器,但我无法让它工作以调用传递的基础应用程序类的静态方法。

interface Constructor<T> {
  new (...args: any[]): T;
  prototype: T;
}

class MockNextApp<P={}>{
    props: P;
    static getInitialProps = (ctx: {}) => {foo:"bar"}

    constructor(props: P) {
        this.props = props;
    }
}

function enhanceApp<T extends Constructor<MockNextApp>>(Base: T) {
    return class extends Base{
        static getInitialProps = (ctx: {}) => {
            return Base.getInitialProps();
        }
    }
}

打字稿错误:

Property 'getInitialProps' does not exist on type 'T'.

您可以查看示例here

【问题讨论】:

    标签: typescript next.js


    【解决方案1】:

    使用Constructor 意味着这将是一个返回MockNextApp 的构造函数,但这并没有说明Base 应该具有的任何其他静态属性。

    我们可以使用包含构造函数签名和函数中所需的额外静态属性的内联类型:

    class MockNextApp<P={}>{
        props: P;
        static getInitialProps = (ctx: {}) => ({foo:"bar"}) // I think you mean to return an object literal, without the (), the arrow function actually returns void.
    
        constructor(props: P) {
            this.props = props;
        }
    }
    
    function enhanceApp<T extends {
        new(...args: any[]): MockNextApp;
        getInitialProps(): { foo: string }
    }>(Base: T) {
        return class extends Base{
            static getInitialProps = (ctx: {}) => {
                return Base.getInitialProps();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      相关资源
      最近更新 更多