javascript - 如何进行运行时转换

标签 javascript typescript casting

我正在使用用 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;
}());

如您所见,member1member2不是编译后的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/

相关文章:

typescript - 如何使 Typescript 检测到带有区分大小写拼写错误的导入路径错误?

reactjs - 用于非类型化 npm 模块的 TypeScript 自定义声明文件

c++ - 检查(原始)类型在 C++ 中是否可转换

generics - Kotlin float/int 间接比较

javascript - Lodash.uniqueId 始终返回 1

javascript - 在 Angular Chart.js 中设置 Y 轴数字的格式

javascript - 将属性设置为未定义时未通知观察者

javascript - 将指定链接中随机选择的照片整合到网页中

javascript - 如何在运行时检查类 B 是否扩展 A

c++ - 向下转换 boost::polymorphic_pointer_downcast 或 boost::dynamic_pointer_cast 哪个更好用