Error occurs when a class contains a static member with the name `name`

Within my TypeScript code, I have a simple class named Foo as part of the Test module.

module Test {
    "use strict";

    class Foo {
        public static name = "foo";
    }
}

However, when I attempt to run this code in Chrome, an error occurs:

I receive an Uncaught TypeError: Cannot assign to read only property 'name' of function 'function Foo() { }'

Upon inspecting the generated JavaScript, here is what it looks like:

var Test;
(function (Test) {
  "use strict";
  var Foo = (function () {
    function Foo() {
    }
    Foo.name = "foo";
    return Foo;
  }());
})(Test || (Test = {}));

If I change the variable name from `name` to something else like `huh`, the error disappears:

module Test {
    "use strict";

    class Foo {
        public static huh = "foo";
    }
}

Why does using the name `name` lead to this issue?

Answer №1

It appears that the issue lies in your attempt to modify the Function.name property. Upon reviewing your initial code, it is evident from the compiled output that you are attempting to alter the Foo.name property.

Please consider the following simplified example:


function Foo(){}
console.log(Foo.name); // returns 'Foo'

The error you are encountering stems from trying to manipulate a read-only property of the function, as explained in more detail here. A big thank you to @ssube for sharing this helpful resource in the comments.

Even though you did not explicitly create the name property, it is inherently present in all functions by default. For further insight, feel free to refer to this page.

Answer №2

In this scenario, the issue arises with Foo.name = "foo";. The problem lies in attempting to redefine the predefined property name of functions in JavaScript. This property, like arguments and length, stores the name of the function (in this case, 'Foo'). Therefore, overriding it with your own value is not possible.

To gain further insights, consider referring to Mozilla's MDN documentation.

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

Using ThreeJS to calculate the rotation needed for one Vector3 to align with another Vector3

Recently delving into the world of ThreeJS, I've been exploring its potential for fun and creativity. My current project involves using ThreeJS in conjunction with aframe. The task at hand requires computing with ThreeJS to pass position and rotation ...

How come it is not possible for me to choose all elements containing an attribute value saved in a variable?

Imagine you have the following snippet of HTML code: <div data-id=5>...</div> <img data-id=5 src=...> <input data-id=5 ...> ... Your task is to select and remove all elements with the attribute data-id set to 5. Here is one attemp ...

Leveraging Angular and HTML to efficiently transfer the selected dropdown value to a TypeScript method upon the user's button click

I am experiencing difficulty accessing the .value and .id properties in {{selectItem}} in order to send them back to the typescript for an HTTP post at a later time. Although there are no specific errors, I have encountered exceptions and have tried search ...

No matter how hard I try, npm refuses to ignore my TypeScript source code file

I have a project that I developed using TypeScript and compiled to JavaScript before publishing it as a CLI tool through npm. However, I am facing an issue where the TypeScript source code is being included in the npm package, along with other random .ts f ...

What is the best method for obtaining accurate normal values in three.js?

I'm having trouble understanding how normals are computed in Three.js. Here is the issue I am facing: I have created a simple plane using the following code: var plane = new THREE.PlaneGeometry(10, 100, 10, 10); var material = new THREE.MeshBasicMa ...

How can HtmlUnit be used to identify and address website pages that display errors?

I've encountered an issue while trying to access this Ajax page through my Java program using the HtmlUnit 2.15 API. It seems that the problem arises from a broken link to a missing file located here. This is the snippet of code I'm working with ...

The error message "UnhandledPromiseRejectionWarning: Error: ENOTEMPTY: directory not empty" typically occurs

Struggling to successfully run the build using npm run build. Encountering the following error: UnhandledPromiseRejectionWarning: Error: ENOTEMPTY: directory not empty, rmdir '/var/www/html/abhinav/png-react/png-compressor/build/static' ...

Calculating the number of digits in a series of numbers, experiencing a timeout issue (What is the page count of a book? from codewars)

Solving the Digits in a Book Problem Find the number of pages in a book based on its summary. For example, if the input summary is 25, then the output should be n=17. This means that the numbers 1 to 17 have a total of 25 digits: 123456789101112131415161 ...

tips for transferring a javascript function value to a label within a webform

Currently, I am in search of the latitude and longitude coordinates for a specific address input by the user. Upon clicking a button, the script provided below is triggered to display an alert with the latitude and longitude values: <script type="text/ ...

Leveraging node.js for website development

After setting up Node.js and installing the latest version of Express 3.4.1, I started coding. However, when trying to send parameters other than /, I encountered an error. In my index.js file, I have the following code: exports.speakers = function(req, ...

Automatically Dismissing a Bootstrap Alert After a Set Number of Seconds

Having some trouble closing a Bootstrap alert automatically on my new site built using the Bootstrap Framework. The issue arises when trying to close the alert after a certain amount of time. On the main page of the site, there is a modal login form. When ...

Another option could be to either find a different solution or to pause the loop until the

Is it possible to delay the execution of a "for" loop until a specific condition is met? I have a popup (Alert) that appears within the loop, prompting the user for confirmation with options to Agree or Cancel. However, the loop does not pause for the co ...

The $.getJSON onComplete function does not pause for the result to be returned

When working with JSON data and calling the loadThumbs(json) event, an error message stating that json is undefined may occur. Upon printing the JSON object to the console, it appears empty. However, if the JSON object is manually printed, it displays co ...

Are there any distinctions between these two compact React components?

Let's compare these two components: function App1 () { return <button onClick={() => null}>Click me</button> } function App2 () { const fn = () => null; return <button onClick={fn}>Click me</button> } The on ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

Creating a Precise Millisecond Countdown Timer using Angular 4 in Javascript

I'm currently facing a challenge in Angular 4 as I attempt to develop a countdown timer that accurately displays milliseconds once the timer falls below 1 minute (59 seconds or less) for a sporting event clock. My issue lies with the setInterval funct ...

Unable to run the command npm run env:restart

Currently, I am in the process of running a basic example. The initial setup involved configuring the convector workspace by installing convector-cli and hurley, as well as performing an npm installation. However, when attempting to execute npm run env:r ...

What is the most streamlined way to send data from HTML forms using solely JavaScript?

I currently employ jQuery to transmit data from my HTML forms and then I utilize PHP to save it in my database. Below is the code snippet that I am using: HTML FORM: <form id="formpost" action="" method="post" onsubmit="return false"> <input t ...

Why won't my redux application store the results of an asynchronous API request using redux-thunk's caching mechanism?

I am new to using Redux in my project. Currently, I am developing an application that displays a list of soccer leagues in each country. The process involves fetching a list of countries first, then using the country names to fetch the soccer leagues. Not ...

Is there a way to stop TinyMCE from adding CDATA to <script> elements and from commenting out <style> elements?

Setting aside the concerns surrounding allowing <script> content within a Web editor, I am fully aware of them. What I am interested in is permitting <style> and <script> elements within the text content. However, every time I attempt to ...