In the context of a child component calling a callback provided by its parent, this situation is commonly seen in AngularJS.
As I am utilizing TypeScript, I aim to implement strong typing for the callback in the child component.
Here is the initial state without any strong typings:
class ParentComponentController {
public parentMethod(param1: number, param2: string): boolean {
return param1 > 0 && param2.length > 2;
}
}
class ChildComponentController {
constructor(private parentMethod: Function) {}
public onCertainTrigger() {
this.parentMethod(10, 'something');
}
}
This is how I can achieve strong typing, but it appears messy:
declare type parentMethod = (param1: number, param2: string) => boolean;
interface ICommonApi {
parentMethod: parentMethod;
}
class ParentComponentController implements ICommonApi {
public parentMethod(param1: number, param2: string): boolean {
return param1 > 0 && param2.length > 2;
}
}
class ChildComponentController {
constructor(private parentMethod: parentMethod) { }
public onCertainTrigger() {
this.parentMethod(10, 'something');
}
}
In an ideal scenario, I envision this being simplified into a one-liner. Is this feasible?
class ParentComponentController {
public parentMethod(param1: number, param2: string): boolean {
return param1 > 0 && param2.length > 2;
}
}
class ChildComponentController {
// This leads to an error
constructor(private parentMethod: ParentComponentController.parentMethod) {}
public onCertainTrigger() {
this.parentMethod(10, 'something');
}
}