0

Due to some reason, I am require to use the eval() and access the function i.e. foo. However, I not able to make it in typescript.

eval("function foo() { console.log(\"foo bar\") }");
// @ts-ignore
foo();

The above code will hit error instead of print "foo bar" in console log.

VM42:4 Uncaught ReferenceError: foo is not defined

You may try the code here.

However, the same code work in javascript.

Does it require additional configuration?

karfai
  • 816
  • 1
  • 10
  • 21
  • Seems like it's just how the TS Playground executes your code. I don't think it's TypeScript specific. As always, I must urge against using `eval` if it's not really needed, though. The issue here might be a side-effect but `eval` is best avoided anyway. – VLAZ Mar 31 '20 at 13:01
  • Actually, I hit the same issue in my ReactJs TypeScript project as well. So I find a simple example to simulate it. – karfai Mar 31 '20 at 13:03

2 Answers2

4

The implied "use strict" of TypeScript puts heavy restrictions on eval, notably its inability to create new symbols. You would need to explicitly return and assign the function from eval:

"use strict"

const foo = eval("function foo() { console.log(\"foo bar\") }; foo;");

foo();
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Using hoist can do. `let foo; eval("function foo() { console.log(\"foo bar\") }"); // @ts-ignore foo();` – xdeepakv Mar 31 '20 at 13:11
  • Nope, not in *strict mode.* – deceze Mar 31 '20 at 13:18
  • For typescript, is it possible to partially disable the 'use strict' for a single code block? – karfai Mar 31 '20 at 13:19
  • 1
    @karfai I believe you can only [*globally* disable it](https://stackoverflow.com/a/38270418/476), which certainly isn't a good idea. Just appending `+ '; foo;'` to your string and using the above solution is the most sensible solution, if you have to use `eval` in the first place. – deceze Mar 31 '20 at 13:22
1

// You can define in window/global. that will be accesable anywhere.

// You can hoist function. Cheat

let foo;
eval('function foo() { console.log("foo bar") };');

// @ts-ignore
foo();

// For browser add in window,

eval("function foo() { console.log(\"foo bar\") }; window.foo = foo");

// @ts-ignore
foo();

// For nodejs add in window,

eval("function foo() { console.log(\"foo bar\") }; global.foo = foo");

// @ts-ignore
foo();
xdeepakv
  • 7,835
  • 2
  • 22
  • 32