2017-07-17 159 views
2

是否有可能將我的Typescript代碼保存爲一個字符串,並在運行期間將其忽略?對於簡單的例子:從字符串評估Typescript?

let code: string = `({ 
    Run: (data: string): string => { 
     console.log(data); return Promise.resolve("SUCCESS"); } 
    })`; 

然後,像這樣運行它:

let runnalbe = eval(code); 
runnable.Run("RUN!").then((result:string)=>{console.log(result);}); 

應打印:

RUN!SUCCESS 
+0

號因爲打字稿不JavaScript和使用'eval'很可能會給你一個語法錯誤。 – d4nyll

+1

Typescript是爲了讓你的代碼更安全而發明的:)將代碼放在字符串中使得它令人難以置信的不安全:) – Kokodoko

回答

2

official TypeScript compiler 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);});