DSPdav
DSPdav

Reputation: 170

TypeScript implementing interface in class

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:

  1. declare interface
interface Notification {
    message: string;
    send(msg?: string): void;
}
  1. implements interface in class with constructor()
class Notifier implements Notification {
    constructor(
        public message: string,
    ){}

    send(customMsg?: string): void {
        if (customMsg) {
            console.log(customMsg);
        } else {
            console.log(this.message);
        }
    }
}
  1. example, using class
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

Answers (1)

jcalz
jcalz

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.

Playground link to code

Upvotes: 1

Related Questions