Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript doesn't have window.eval()

Tags:

In JavaScript I can do:

window.eval(userInput)

in a client-side .js file without any issue.

But in TypeScript, window.eval() does not exist. I get the error:

property eval does not exist on type window

How can I get around this issue?

The reason I want to use eval() is to execute some user created code. The eval call must be done on a global scope because the user code relies on some other code that I have already previously loaded with <script> tags.

like image 879
Roymunson Avatar asked Jul 17 '18 22:07

Roymunson


People also ask

Can you use eval in TypeScript?

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. Also, setTimeout and setInterval functions can both run code from a string.

Is eval deprecated?

Question : The 'eval' method within JavaScript / DemandwareScript is deprecated based on the potential security risks by using this method as it doesn't escape input parameters. Answer : You should use the 'new Function()' instead.

Which is faster eval () or new function?

`Function() is a faster and more secure alternative to eval().

Why is it bad to use eval?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!


1 Answers

There are a couple of ways to do this.

Use type assertion (Type unsafe, but quick and easy):

(window as any).eval("1 + 1");

Or you can modify the window declaration as described in this issue (Type safe)

like image 166
youngwerth Avatar answered Sep 28 '22 17:09

youngwerth