Typescript class 增强器和静态方法

Typescript class enhancer and static methods

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

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

使用 Constructor 意味着这将是 returns 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();
        }
    }
}