Function cannot be accessed following the execution of eval()

For some unknown reason, I need to utilize the eval() function and access a specific function called foo. Unfortunately, I am struggling to achieve this in TypeScript.

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

Instead of printing "foo bar" in the console log, the code above throws an error.

VM42:4 Uncaught ReferenceError: foo is not defined

You can experiment with the code snippet here.

However, the same code works perfectly fine in JavaScript.

Do you think additional configuration is needed?

Answer №1

One of the main restrictions imposed by TypeScript's implicit "use strict" is on the use of eval, specifically its inability to create new symbols. To work around this, you must explicitly return and assign the function from within the eval:

"use strict"

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

bar();

Answer №2

// To make a function accessible globally, you can define it in the window/global object.

// You have the option to "hoist" a function using a cheat method.

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

// @ts-ignore
foo();

// For browser compatibility, add the function to the window object.

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

// @ts-ignore
foo();

// For node.js compatibility, add the function to the global object.

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

// @ts-ignore
foo();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to include a lockfile in a docker container as an optional step?

I am attempting to create a docker image that can optionally incorporate a yarn or npm lockfile during the build process. I want to include it explicitly, but also ensure that the build does not fail if the lockfile is missing. The goal is to respect dete ...

Selenium server is not running and causing a connection refusal

Recently, I took over a project at work that lacks any documentation. The project is built on sails.js and includes a small number of unit tests along with an end-to-end test. Unfortunately, when attempting to execute the end-to-end test using grunt, the ...

The error message indicated that a Promise<string> was expected, but instead a Promise<string|number> was received

Confusion Over Promise Type Error How did the TypeScript compiler generate the error message displaying Type Promise <string|number> ... in the following scenario? Type 'Promise<string | number>' is not assignable to type 'Prom ...

What could be causing my Angular.js controller to run its function twice in this code snippet?

Currently, I have an ng-repeat in place, looping through an array of objects that are associated with the SomeController: <div ng-controller="SomeController as aCtrl"> <div ng-repeat="category in aCtrl.categories"> <p ng-show="aCtrl.c ...

Ways to combine two arrays using dual requests in JavaScript with Mailchimp

The issue with the title not being very clear has been noted. Allow me to elaborate on my problem. Below is the code snippet: mailchimpMarketing = require("@mailchimp/mailchimp_marketing"); mailchimpMarketing.setConfig({ apiKey: "MY API KEY", server: "MY ...

One file successfully imports a dependency, while the other file does not seem to recognize it

I'm diving into the world of Vuex, exploring how to create an auth module. I came across some examples that I'm trying to implement, but I've hit a roadblock when attempting to use axios in my store. My store is structured with separate file ...

Switching a jQuery AJAX Response

Currently, I am utilizing an AJAX function to retrieve and display specific categorical posts when a corresponding button is clicked: <script> // Brochure AJAX function term_ajax_get(termID) { jQuery("#loading-animation").show(); ...

Using jQuery Ajax in ASP.NET MVC to send arguments from JavaScript via POST requests

I have a controller action in ASP.NET MVC that has the following signature in VB.NET: <HttpPost()> Public Function ClosestCities (ByVal position As MapCoordinate, ByVal citiesCount As UInteger) As JsonResult The MapCordinate class is defined as ...

Organizing tooltip data for two line charts with D3 and AngularJS

I've encountered an issue with a simple example involving 2 line charts with bullets. When hovering over the bullets, tooltips appear showing values that correspond to the y-axis frequency values. However, I'm struggling to determine which node ( ...

Angular utilizes a factory within a model to return specific values

My factory is set up with a model that is functioning well, but I am facing difficulty in setting up a function inside it to return a value when called. The issue could be related to syntax or my approach towards it. Here is the code snippet: .factory(&ap ...

displaying and activating element using jQuery

I'm currently working on setting up a notification system for my website but seem to be encountering some issues that I can't quite pinpoint. Essentially, I have a link that triggers a JavaScript function upon being clicked. This function is mean ...

Is it possible to have the front-facing photo in expo-camera stay mirrored?

Currently, I am utilizing the expo-camera library to capture a selfie image. Despite the preview being mirrored, the final saved image reverts to its normal orientation. Is there any way to avoid this behavior so that the image remains mirrored? Alternativ ...

How can a state declaration accommodate a conditional statement?

I'm currently tackling a form on a website using React JSX. Depending on the user's access level, they should have visibility and ability to manipulate different fields within the form. I recently joined this project (I'm fairly new to React ...

Typescript or Angular 2 for Google Maps

Is there a way to integrate Google Maps Javascript API with Typescript or Angular 2? Although libraries like https://github.com/SebastianM/angular2-google-maps are available, they may not provide full support for features like Events and Places Libraries ...

"Efficient Implementation: Expo React Native Utilizes Custom Font Loading One Time Only

Hello everyone, I'm a newcomer here and I'm currently using Expo to build a react native app. My goal is to implement custom fonts in my project. I've gone through the documentation which can be found here. However, I'm facing an issue ...

The blending scene in Three.js is flickering with the EffectComposer

I'm a beginner in three.js and I am facing challenges in achieving a specific effect: rendering 2 scenes and blending them with a shader. The first TexturePass is working fine, but the second one is flickering like a strobe light. You can see the resu ...

Using AngularJS to filter an array using the $filter function

Looking for a more elegant way to achieve the following task: myList.forEach(function(element){ if (!['state1', 'state2'].contains(element.state)){ myFilteredList.push(element) } }) I was thinking of using $filter('fi ...

Refresh tab controllers in Angular JS on every click event

Is there a way to refresh the tab controller every time a tab is clicked? Here's the current code: $scope.tabs = [ { id: 'tab1', title: 'tab1', icon: 'comments', templateUrl: 'tab1/tab1.tpl.html&ap ...

When using the jQuery datepicker with the minDate set to 0, any past dates entered in the text box will be automatically reset to the current date

How can I prevent users from selecting past dates in a jQuery datepicker, while keeping any existing past dates displayed as is? My current code looks like this: $("#t1").datepicker({ minDate:0 }); And the text box code is, <input type="t1" va ...

In Angular, providing a value in a form may not always hold true to its actual worth

Having an issue where the value passed from TypeScript to an input element is displayed on the screen, but the ngForm parameters show that the value is empty and the form is invalid. Here is the HTML component: <form #editForm="ngForm" (ngSub ...