Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods with different signatures or non-method members, I've implemented the following approach:
interface IRequestParser {
[funcName: string]: (...args: any[]) => string;
}
Here's an illustration using a sample class:
class myParser implements IRequestParser {
[funcName: string]: (...args: any[]) => string;
func1(a) {
return '';
}
}
This design restriction prohibits the inclusion of properties that are not methods within myParser
:
a: string; // not allowed
b() { // not allowed
return 5;
}
However, it enables me to invoke any function from an instance of myParser
without raising an alert:
const instance = new myParser();
console.log(instance.func1('sample'));
console.log(instance.func2(4, 5, ['a', 'b']));
While calling func1
is expected behavior and would trigger an error if missing the required argument, there is also the ability to call a non-existent function like func2
or any arbitrary name.
Is there a method to restrict the type of class members while preventing the invocation of undefined functions?