When working on a web application written in TypeScript, there is a feature where users can add additional JavaScript functions that will be parsed at runtime (new function(Function as String)
) for execution. These functions should return an object defined in TypeScript as class Script
. However, if the script object does not contain specific functions, it is considered invalid. My goal is to throw an exception if any required functions are missing.
Using a TypeScript cast is not viable as it is a compile-time operation.
One approach I thought of is to assign the parsed object to the Script
object's constructor and then check for missing properties. Here is a rough example to illustrate the idea:
export class Script {
constructor(object: Script) {
this.getDefaultValue = object.getDefaultValue;
this.isAvailable = object.isAvailable;
this.isValid = object.isValid;
this.isInRange = object.isInRange;
this.isDataFormat = object.isDataFormat;
for (let property in this){
if (!this[property]){
throw new Error(property + ' is missing.');
}
}
}
getDefaultValue: any;
isAvailable: (containerSetId: number) => boolean;
isValid: (value: any) => boolean;
isInRange: (value: any) => any;
isDataFormat: (value: any) => boolean;
}
However, I am wondering if there is a more elegant solution to handle this scenario.