Javascript Typescript:使用接口从字符串创建函数

Javascript Typescript:使用接口从字符串创建函数,javascript,typescript,Javascript,Typescript,我有一些保存在字符串中的逻辑,我需要将其转换为可运行函数。我已经设置了接口,使其在Typescript中强类型,但它似乎不起作用 interface IInterface { Run(data: string): Promise<string>; } let code: string = ` return new class{ let Run = function(data) { console.log(data);

我有一些保存在字符串中的逻辑,我需要将其转换为可运行函数。我已经设置了接口,使其在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);
});
接口界面{
运行(数据:字符串):承诺;
}
let代码:字符串=`
返回新类{
让运行=函数(数据){
控制台日志(数据);
返回“成功”;
};
}
`;
让obj:IInterface=函数(代码)作为IInterface;
运行(“测试”)。然后((结果:字符串)=>{
控制台日志(结果);
});

应该写:testsuccess

您通过
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));
接口界面{
运行(数据:字符串):承诺;
}
var f:IInterface=eval(`({run:function(data){console.log(data);return Promise.resolve(“SUCCESS”);}}}});
f、 运行(“helloworld”)。然后(x=>console.log(x));

应该像你期望的那样打印

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