【问题标题】:Defining a class parent with same methods but different constructors in typescript在打字稿中使用相同的方法但不同的构造函数定义类父
【发布时间】:2023-02-09 04:41:09
【问题描述】:

我有这段代码:

class A {
    constructor(
        private _a: number,
    ) {}

    method1() {}
    method2() {}
}

class B {
    constructor(
        private _b: number,
    ) {}

    method1() {}
    method2() {}
}

class C {
    constructor(
        private _c: number,
    ) {}

    method1() {}
    method2() {}
}

let list = [new A(1), new B(2), new C(3)];
list.forEach((element: any) => {
    element.method1();
})
 

我有这三个具有相同名称的不同构造函数和方法的类。

我如何替换 typescript 的 any 类型以知道 method1 存在?

【问题讨论】:

  • Typescript 推断list 的元素只能是ABC。由于所有这三个都有 method1,从技术上讲,您可以省略 .forEach() 中的类型,因为它会自动推断为 A | B | C

标签: typescript class object oop inheritance


【解决方案1】:

好吧,基本上它已经在 cmets 中了,但是由于没有答案:最直接的方法是创建一个新类型:

class A {
    constructor(
        private _a: number,
    ) {}

    public commonMethod() {
      console.log("A")
    }
}

class B {
    constructor(
        private _b: number,
    ) {}

    public commonMethod() {
      console.log("B")
    }
}

class C {
    constructor(
        private _c: number,
    ) {}

    public commonMethod() {
      console.log("C")
    }
}

type letters = A | B | C

let list = [new A(1), new B(2), new C(3)];
list.forEach((element: letters) => {
    element.commonMethod();
})
 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2015-08-29
    • 2015-10-26
    • 2017-01-29
    相关资源
    最近更新 更多