typescript 从字符串评估打字稿?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45153848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Evaluate Typescript from string?
提问by Bill Software Engineer
Is it possible to save my Typescript code in a string and evaulate it during run time? For simple example:
是否可以将我的 Typescript 代码保存在字符串中并在运行时对其进行评估?举个简单的例子:
let code: string = `({
Run: (data: string): string => {
console.log(data); return Promise.resolve("SUCCESS"); }
})`;
Then run it like this:
然后像这样运行它:
let runnalbe = eval(code);
runnable.Run("RUN!").then((result:string)=>{console.log(result);});
Should print:
应该打印:
RUN!SUCCESS
采纳答案by Saravana
The official TypeScript compiler APIprovides a way to transpile source strings:
在正式打字编译器API提供了一种transpile源字符串:
import * as ts from "typescript";
let code: string = `({
Run: (data: string): string => {
console.log(data); return Promise.resolve("SUCCESS"); }
})`;
let result = ts.transpile(code);
let runnalbe :any = eval(result);
runnalbe.Run("RUN!").then((result:string)=>{console.log(result);});
回答by basarat
Is it possible to save my Typescript code in a string and evaulate it during run time
是否可以将我的 Typescript 代码保存在字符串中并在运行时对其进行评估
Yes. By using the TypeScript compiler's transpile
function.
是的。通过使用 TypeScript 编译器的transpile
函数。
More
更多的
Checkout TypeScript - Script : https://github.com/basarat/typescript-scriptwhich at it's core is simply ts.transpile
: https://github.com/basarat/typescript-script/blob/163388be673a56128cc1e1b3c76588001a8c1b18/transpiler.js#L60
结帐 TypeScript - 脚本:https: //github.com/basarat/typescript-script,其核心很简单ts.transpile
:https: //github.com/basarat/typescript-script/blob/163388be673a56128cc1e1b3c76588001a8c1b18/transpiler.js#L