Typescript types on rest params from argument -
is possible tell typescript types of rest params based on signature of function passed?
function myfunc(a: string, b: number) { /* ... */ } function callfn(passedfn: (args...: any[]), ...args: any[]) { passedfn(...args) } callfn(myfunc, 1, 2) // should warning
following code shows compile error, because lose type control under args.
interface icallback { (a: string, b: number): void } class test { public callfn(passedfn: icallback, ...args: any[]): void { passedfn(args); // error passedfn("1", 2); } } class callback { public myfunction = (a: string, b: number) => { alert("it's working"); } } let testintance = new test(); let callbackintance = new callback(); testintance.callfn(callbackintance.myfunction, 1, 2);
you have handle exceptions , try parse typed variables.
class test { public callfn(passedfn: icallback, ...args: any[]): void { //passedfn(args); // error let hastwoarguments = args && args.length && args.length === 2; if(!hastwoarguments) { return; } let firstargument: string = args[0]; let secondargument: number = parseint(args[1]); passedfn(firstargument, secondargument); } }
see demo
Comments
Post a Comment