在接口中设置构造函数
Set constructor in interface
我有一个接口和一个实现它的 class
export interface ITooltip {
new(elem: HTMLElement, options?: ITooltipOptions);
show(): void;
hide(): void;
toggle(): void;
}
export class Tooltip implements ITooltip {
constructor(private elem: HTMLElement, private options?: ITooltipOptions) {
}
....
}
但是在控制台我有一个错误:
Class 'Tooltip' incorrectly implements interface 'ITooltip'.
Type 'Tooltip' provides no match for the signature 'new (elem: HTMLElement, options?: ITooltipOptions): any'
我不明白为什么会出现这个错误。
您的代码中包含一些内容:
首先,在 Typescript 中,您的 class 必须提供接口中定义的所有字段和函数。这有时可能很乏味。如果你想避免这种情况并且它不会破坏你的结构,你可以使用 extends 而不是 implements 然后你不需要重新定义一切
其次,您没有在接口中声明构造函数声明。所以new(....
句应该去掉。
您的代码最终将如下所示:
export interface ITooltip {
show(): void;
hide(): void;
toggle(): void;
}
export class Tooltip implements ITooltip {
constructor(elem: HTMLElement, options?: ITooltipOptions) {};
show(): void {};
hide(): void {};
toggle(): void {};
}
无论如何我建议你先阅读打字稿的文档来理解这些概念
据我所知,您不能将 class 实现的接口与 class 构造函数接口结合起来。
这个有效:
export interface ITooltip {
show(): void;
hide(): void;
toggle(): void;
}
export type TooltipConstructor = { new(elem: HTMLElement, options?: ITooltipOptions): Tooltip };
export class Tooltip implements ITooltip {
constructor(private elem: HTMLElement, private options?: ITooltipOptions) {}
show(): void {}
hide(): void {}
toggle(): void {}
}
我有一个接口和一个实现它的 class
export interface ITooltip {
new(elem: HTMLElement, options?: ITooltipOptions);
show(): void;
hide(): void;
toggle(): void;
}
export class Tooltip implements ITooltip {
constructor(private elem: HTMLElement, private options?: ITooltipOptions) {
}
....
}
但是在控制台我有一个错误:
Class 'Tooltip' incorrectly implements interface 'ITooltip'.
Type 'Tooltip' provides no match for the signature 'new (elem: HTMLElement, options?: ITooltipOptions): any'
我不明白为什么会出现这个错误。
您的代码中包含一些内容:
首先,在 Typescript 中,您的 class 必须提供接口中定义的所有字段和函数。这有时可能很乏味。如果你想避免这种情况并且它不会破坏你的结构,你可以使用 extends 而不是 implements 然后你不需要重新定义一切
其次,您没有在接口中声明构造函数声明。所以new(....
句应该去掉。
您的代码最终将如下所示:
export interface ITooltip {
show(): void;
hide(): void;
toggle(): void;
}
export class Tooltip implements ITooltip {
constructor(elem: HTMLElement, options?: ITooltipOptions) {};
show(): void {};
hide(): void {};
toggle(): void {};
}
无论如何我建议你先阅读打字稿的文档来理解这些概念
据我所知,您不能将 class 实现的接口与 class 构造函数接口结合起来。
这个有效:
export interface ITooltip {
show(): void;
hide(): void;
toggle(): void;
}
export type TooltipConstructor = { new(elem: HTMLElement, options?: ITooltipOptions): Tooltip };
export class Tooltip implements ITooltip {
constructor(private elem: HTMLElement, private options?: ITooltipOptions) {}
show(): void {}
hide(): void {}
toggle(): void {}
}