简体   繁体   中英

Arrow function in typescript interface with return type as void

I am trying to write arrow function in my type Script interface as below but getting error "Class 'ToastrService' incorrectly implements interface 'IToastr'."

interface IToastr{
    (message:string,title:string):void;
}

@Injectable()
export class ToastrService implements IToastr {
    (message:string,title:string):void {
         toastr.success(message,title);
    }
}

My question is: can we define a function signature in TS interface with return type as void??

I did try searching google as well but did not find any example. Thanks !!

What you are doing seems fine just missing a name for the function (or if this is a constructor then the constructor keyword is missing)

interface IToastr{
    toast(message:string,title:string):void;
}

@Injectable()
export class ToastrService implements IToastr {
    toast(message:string,title:string):void {
         toastr.success(message,title);
    }
}

Yes it is possible. Please consult the official typescript for more info.

Example 1:

interface SearchFunc {
    (source: string, subString: string): void;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    // do smth
}

Example 2: Solution: You should name your function

interface IToastr{
    FuncName(message:string,title:string):void;
}

class ToastrService implements IToastr {
    FuncName(message:string,title:string):void {
         // toastr.success(message,title);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM