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.
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.
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.
`Function() is a faster and more secure alternative to 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!
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)
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