karfai
karfai

Reputation: 906

Not able access function after eval()

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?

Upvotes: 0

Views: 669

Answers (2)

xdeepakv
xdeepakv

Reputation: 8135

// 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();

Upvotes: 1

deceze
deceze

Reputation: 522210

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();

Upvotes: 5

Related Questions