Home > other >  typescript remind cannot assign type '(x: string) => void' to type '() => void
typescript remind cannot assign type '(x: string) => void' to type '() => void

Time:06-08

I used the code, defined an interface, and made a function, but when the subclass uses the function defined by the interface, an error occurs, prompting cannot assign type '(x: string) => void' to type '() => void

interface People{
  speak():void;
}

class Anny implements People {
  name:string = 'anny';

  speak(x:string):void {
    console.log(this.name, x);
  }
}
const annyObj = new Anny();
annyObj.speak('hello');

CodePudding user response:

You have to change the speak method parameter to nullable:

class Anny implements People {
    name: string = 'anny'
    // x is nullable
    speak(x?: string): void {
        console.log(this.name, x)
    }
}
  • Related