如何在 TypeScript 的已实现接口中进行构造函数重载?
How can I do constructor overloading in a implemented interface in TypeScript?
我试图重载实现接口的 class 的构造函数,但出现以下错误:
[0] app/foo.ts(12,5): error TS2394: Overload signature is not compatible with function implementation.
类
export interface Item {
time: number;
}
export class Foo implements Item {
public time: number;
public name: string;
constructor();
constructor(
time: number,
name: string
) {
this.time = id || -1
this.name = name || ""
};
}
我发现了其他类似的问题 (Constructor overload in TypeScript),但我遗漏了一些东西,因为它不起作用。打字稿版本是 1.8.9.
实现签名不可见。您需要声明 所有 调用者应该看到的重载,然后编写实现主体。
export interface Item {
time: number;
}
export class Foo implements Item {
public time: number;
public name: string;
constructor();
constructor(
time: number,
name: string
);
constructor(
time?: number,
name?: string
) {
this.time = id || -1
this.name = name || ""
};
}
您还可以阅读 TypeScript FAQ entry on this
我试图重载实现接口的 class 的构造函数,但出现以下错误:
[0] app/foo.ts(12,5): error TS2394: Overload signature is not compatible with function implementation.
类
export interface Item {
time: number;
}
export class Foo implements Item {
public time: number;
public name: string;
constructor();
constructor(
time: number,
name: string
) {
this.time = id || -1
this.name = name || ""
};
}
我发现了其他类似的问题 (Constructor overload in TypeScript),但我遗漏了一些东西,因为它不起作用。打字稿版本是 1.8.9.
实现签名不可见。您需要声明 所有 调用者应该看到的重载,然后编写实现主体。
export interface Item {
time: number;
}
export class Foo implements Item {
public time: number;
public name: string;
constructor();
constructor(
time: number,
name: string
);
constructor(
time?: number,
name?: string
) {
this.time = id || -1
this.name = name || ""
};
}
您还可以阅读 TypeScript FAQ entry on this