Reputation: 170
I am new in TypeScript, could anyone help me to figure it out the best practices with implementing interface in class? Because when I tried to following the Docs (Class Heritage), I caught in some problem like so:
interface Notification {
message: string;
send(msg?: string): void;
}
constructor()
class Notifier implements Notification {
constructor(
public message: string,
){}
send(customMsg?: string): void {
if (customMsg) {
console.log(customMsg);
} else {
console.log(this.message);
}
}
}
const hello = new Notifier("hello");
hello.send();
hello.send("Alert!");
Unfortunately, I found an error message like the following:
Class 'Notifier' incorrectly implements interface 'Notification'. Type 'Notifier' is missing the following properties from type 'Notification': actions, badge, body, data, and 19 more.
Could anyone tell me what is my wrong? Thanks in advance!
Upvotes: 1
Views: 474
Reputation: 327624
Your problem is that the TypeScript standard library already includes a globally-scoped interface
named Notification
corresponding to the Notification
interface from the Web Workers API. Because of this, your Notification
interface
definition is just merging additional members into it. This is obviously not what you intend.
The fix here is either to rename your interface
to something else like MyNotification
, or create a module
or namespace
that creates a new naming scope for your code:
// use of "export" makes your code a module
export interface Notification {
message: string;
send(msg?: string): void;
}
or
namespace MyNamespace {
export interface Notification {
message: string;
send(msg?: string): void;
}
}
And then you should be able to refer to it later. If you use the namespace
approach, you'll get this:
class Notifier implements MyNamespace.Notification {
constructor(
public message: string,
) { }
send(customMsg?: string): void {
if (customMsg) {
console.log(customMsg);
} else {
console.log(this.message);
}
}
}
const hello = new Notifier("hello");
hello.send();
hello.send("Alert!");
Which works as desired.
Upvotes: 1