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
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.
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.
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.
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().
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);});
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With