In my app I have several classes which are used to create XML strings. Each class has a few methods that take some arguments and return a string. I want to specify this limitation so that methods with a different signature or other class members can't be added. To this end, here's where I got so far:
interface IRequestParser {
[funcName: string]: (...args: any[]) => string;
}
and an example of a class:
class myParser implements IRequestParser {
[funcName: string]: (...args: any[]) => string;
func1(a) {
return '';
}
}
This prevents me from adding functions that don't return strings, or any other non-method member, so these aren't allowed inside myParser
:
a: string; // not allowed
b() { // not allowed
return 5;
}
However, this has the effect of letting me call any function name from an instance of myParser
without an alert:
const a = new myParser();
console.log(a.func1('a'));
console.log(a.func2(4, 5, ['s', 'b']));
The call to func1
makes sense and I would also get an error if I didn't supply a value for its argument a
. However, I can also call non-existing function func2
and any other name.
Is there a way to both limit the type of class members while also avoiding this situation of calling any function with any name?