Home > Net >  Typescript interface for a class method error
Typescript interface for a class method error

Time:09-28

Why do I get error "the string is not assignable to iGreet" ?

  interface iGreet {
    (p: string ): string
  }


  class C {
    greeting: string;

    constructor(message: string) {
      this.greeting = message;
    }

    greet(p: string): iGreet {
      return "Hello, "   this.greeting   " "   p;
    } 
  }

  let greeter = new C("world");
  console.log(greeter.greet("test"))

CodePudding user response:

greet(p: string): iGreet is saying this function returns iGreet. If you want to annotate the type of greet, you'll need to use an assignment like this:

greet: iGreet = function (p) {
    // ...
}
  • Related