我正在使用用 TypeScript 编写的 Web 应用程序。在应用程序的一部分中,用户可以编写一个附加的 JavaScript 函数,该函数将在运行时解析(new function(Function as String)
)以供执行。该代码将返回一个我在 TypeScript 中定义为 class Script
的对象。该脚本对象应包含特定的函数,否则无效。意思是,如果用户未实现一个或多个功能,我想抛出异常。
Typescript 转换无法做到这一点,因为它是编译时转换。
我考虑过为 Script
对象提供一个构造函数,该构造函数接受解析的对象(根据键/值,应该已经是一个 Script
对象)并检查该对象在构造函数中查找缺失的属性。
像这样的东西:
(这行不通,它只能显示想法)
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 propertie in this){
if (!this[propertie]){
throw new Error(propertie+ ' is missing.');
}
}
}
getDefaultValue: any;
isAvailable: (containerSetId: number) => boolean;
isValid: (value: any) => boolean;
isInRange: (value: any) => any;
isDataFormat: (value: any) => boolean;
}
但是有没有更好的方法来做到这一点?
最佳答案
你不能使用它,因为:
class A {
member1: string;
member2: number;
member3: boolean;
constructor() {
this.member3 = true;
}
}
编译为:
var A = (function () {
function A() {
this.member3 = true;
}
return A;
}());
如您所见,member1
和member2
不是编译后的js版本的一部分。
您需要跟踪运行时所需的属性,例如:
class Script {
getDefaultValue: any;
isAvailable: (containerSetId: number) => boolean;
isValid: (value: any) => boolean;
isInRange: (value: any) => any;
isDataFormat: (value: any) => boolean;
required = [
"getDefaultValue",
"isAvailable",
"isValid",
"isInRange",
"isDataFormat"
]
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 propertie in this.required) {
if (!this[propertie] || typeof this[propertie] !== "function") {
throw new Error(propertie+ ' is missing.');
}
}
}
}
关于javascript - 如何进行运行时转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953828/