gpt4 book ai didi

javascript - Typescript:使用接口(interface)从字符串创建函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:56 26 4
gpt4 key购买 nike

我有一些逻辑保存在字符串中,我需要将其转换为可运行的函数。我已经设置了 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);
});

应该写:测试成功

最佳答案

您可以通过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));

应该按您的预期打印。

关于javascript - Typescript:使用接口(interface)从字符串创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45066023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com