Typescript继承,子类有没有方便一点的构造器使用方法?

正常父类的构造器里会用到一些单例工具类,而且这种后续还会增加。例如:

export class ClassA {

    constructor(
        public s1: ServiceA,
        public s2: ServiceB,
        public s3: ServiceC,
    ) {
    }
}

export class ClassB extends ClassA {

    constructor(
        public s1: ServiceA,
        public s2: ServiceB,
        public s3: ServiceC,
    ) {
        super(s1, s2, s3);
    }
}

子类必须调父类构造器,这种传参代码,每次复制粘贴。主要是后续增加一个参数,每个子类都得改过去。
就不能设计成子类默认就有一样的构造器,已经隐式调用了super,别让人手写

阅读 1.2k
3 个回答

可以使用装饰器试试

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

function AutoSuper<T extends Constructor>(constructor: T) {
    return class extends constructor {
        constructor(...args: any[]) {
            super(...args);
        }
    };
}


export class ClassA {

    constructor(
        public s1: number,
        public s2: number,
        public s3: number,
    ) {
    }
}

@AutoSuper
export class ClassB extends ClassA {
}

如果还有其他操作,可以试试

type Constructor<T = {initData: Function}> = new (...args: any[]) => T;

function AutoSuper<T extends Constructor>(constructor: T) {
    return class extends constructor {
        constructor(...args: any[]) {
            super(...args);
            this.initData(...args);
        }
    };
}

class ClassA {
    public s1: number;

    constructor(
        s1: number,
        s2: number,
        s3: number,
    ) {
        this.s1 = s1;
    }
}

@AutoSuper
class ClassB extends ClassA {
    public temp: number = 0;

    initData(s1: number) {
        this.temp = s1;
    }

    prt() {
        console.log('this.s1', this.s1);
        console.log('this.temp', this.temp);
    }
}

const t = new ClassB(1, 2, 3);
t.prt();

如果子类构造只是单纯的调用父类构造,没有增加任何逻辑,那可以省略不写。

snipaste_2024-02-04_23-12-34.png

export class ClassA {
    constructor(
        public s1: ServiceA,
        public s2: ServiceB,
        public s3: ServiceC,
    ) {
    }
}

export class ClassB extends ClassA {
    constructor(...args: ConstructorParameters<typeof ClassA>) {
        super(...args);
    }
}
logo
Microsoft
子站问答
访问
宣传栏