Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Typescript from string?

Tags:

Is it possible to save my Typescript code in a string and evaulate it during run time? For simple example:

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
like image 865
Bill Software Engineer Avatar asked Jul 17 '17 21:07

Bill Software Engineer


People also ask

Can you use eval in TypeScript?

Don't Use eval-Like Methods In JavaScript and by extension, TypeScript, both have methods that take strings and run them as code. There's the eval method which runs code from a string. The Function constructor also returns a function from a string.

How do you evaluate a string in JavaScript?

eval() is a function property of the global object. The argument of the eval() function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code.

How do you define a string value in TypeScript?

In TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string.

How do you use eval instead of function?

An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().


2 Answers

The official TypeScript compiler API provides a way to transpile source strings:

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);});
like image 172
Saravana Avatar answered Sep 22 '22 14:09

Saravana


Is it possible to save my Typescript code in a string and evaulate it during run time

Yes. By using the TypeScript compiler's transpile function.

More

Checkout TypeScript - Script : https://github.com/basarat/typescript-script which at it's core is simply ts.transpile : https://github.com/basarat/typescript-script/blob/163388be673a56128cc1e1b3c76588001a8c1b18/transpiler.js#L60

like image 26
basarat Avatar answered Sep 19 '22 14:09

basarat