0

I have a string that contains multiple JavaScript methods. I want to be able to convert this JavaScript into callable functions within my TypeScript code.

Ex:

script = 'function func1 () { console.log("func1"); } function func2 () { console.log("func2"); }';
// ...
// Magic
// ...
func1();
Ali
  • 1,442
  • 1
  • 15
  • 29
  • Not much you can do besides creating a separate file with that content, you would also have to export the two functions... – Ruan Mendes Jul 27 '17 at 18:59
  • 1
    Basically: [eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) – Nitzan Tomer Jul 27 '17 at 18:59
  • 1
    Eval will not allow TypeScript to call it, it doesn't have access to the definitions – Ruan Mendes Jul 27 '17 at 19:01
  • What is the point here exactly? If you have functions that you're actually going to call in your code, **hardcoded**, then why put them in a string? – Nitzan Tomer Jul 27 '17 at 19:04
  • @NitzanTomer This is simplified version. I need to get a script from the web (which is dynamic) and use functions from that script. – Ali Jul 27 '17 at 19:06
  • @NitzanTomer Got it to work. eval was the answer but it had to be accessed from the native window object. window.eval(script); – Ali Jul 27 '17 at 19:07

0 Answers0