【问题标题】:Typescript: Create Function From String with Interface打字稿:使用接口从字符串创建函数
【发布时间】:2017-07-13 03:48:33
【问题描述】:

我有一些逻辑保存在一个字符串中,我需要将它转换为一个可运行的函数。我已经设置了 Interface 以使其在 Typescript 中强类型化,但它似乎不起作用。

interface IInterface {
    Run(data: string): Promise<string>;
}
let code: string = `
    return new class{
        let Run = function(data) {
            console.log(data);
            return "SUCCESS";
        };
    }
`;
let obj: IInterface = Function(code) as IInterface;
obj.Run("Test ").then((result: string ) => {
    console.log(result);
});

应该写:测试成功

【问题讨论】:

  • 这是您需要使用的实际文本,还是您可以更改语法使其成为真正的 javascript?
  • 语法可以改,我只是写了一些测试代码。

标签: javascript typescript


【解决方案1】:

您通过eval 评估存储在字符串中的javascript。

interface IInterface {
  run(data: string): Promise<string>;
}

var f: IInterface = eval(`({run: function(data) { console.log(data); return Promise.resolve("SUCCESS"); } })`);

f.run("hello world").then(x=>console.log(x));

应该按您的预期打印。

【讨论】:

    猜你喜欢
    • 2013-01-26
    • 2021-12-08
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2022-01-24
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多