英文:
Defining a class parent with same methods but different constructors in typescript
问题
如何替换 any
类型,以使 TypeScript 知道 method1
存在?
你可以使用 TypeScript 的类型推断来解决这个问题。你可以为每个类创建一个共享的接口,以表示它们都有 method1
方法,然后在 forEach
中使用该接口来指定类型。这样,TypeScript 将知道每个元素都有 method1
方法。以下是示例代码:
interface HasMethod1 {
method1(): void;
}
class A implements HasMethod1 {
constructor(private _a: number) {}
method1() {}
method2() {}
}
class B implements HasMethod1 {
constructor(private _b: number) {}
method1() {}
method2() {}
}
class C implements HasMethod1 {
constructor(private _c: number) {}
method1() {}
method2() {}
}
let list: HasMethod1[] = [new A(1), new B(2), new C(3)];
list.forEach((element) => {
element.method1();
});
通过在类上实现 HasMethod1
接口,并将数组类型指定为 HasMethod1[]
,TypeScript 将能够知道 method1
存在于每个元素中,而不再需要使用 any
类型。
英文:
I have this code:
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();
})
I have these three classes with different constructors and methods with the same name.
How do i replace the any
type for typescript to know that method1 exists?
答案1
得分: 1
以下是您要翻译的内容:
Well, basically it was already in comments, but since the answer is absent: the most straightforward way is to create a new type:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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();
})
<!-- end snippet -->
英文:
Well, basically it was already in comments, but since the answer is absent: the most straightforward way is to create a new type:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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();
})
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论