JavaScript Generated From TypeScript Encountering TypeError

Why is the JavaScript code produced by this TypeScript snippet causing a TypeError upon execution?

class Foo {
  public foo: {
    bar: number
  };

  constructor() {
    this.foo["bar"] = 123;
  }
}

new Foo();

Even though I'm compiling it with the --strict option and expecting errors for uninitialized variables, the code still generates an error.

C:\Users\Simon\test.js:4
        this.foo["bar"] = 123;
                        ^

TypeError: Cannot set property 'bar' of undefined
    at new Foo (C:\Users\Simon\test.js:4:25)
    at Object.<anonymous> (C:\Users\Simon\test.js:8:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)

The version of TypeScript being used in this case is 2.5.3.

Answer №1

My expertise lies more within the realm of JavaScript, so TypeScript is not my forte.

After experimenting on the playground, I found that your code compiles as shown below. It's worth noting that with `this.foo["bar"]`, TypeScript won't raise any issues if you use `this.foo["bar-the-third"]`, but I assume you intended to write `this.foo.bar`.

class Foo {
  public foo: {
    bar: number
  };

  constructor() {
    this.foo.bar = 123;
  }
}

new Foo();

Upon examining the output, it seems that TypeScript does not automatically generate the object; you would need to do that yourself. Essentially, TypeScript focuses on type-checking rather than autogenerating code. If you create the object, TypeScript will perform the necessary checks for you.

For instance,

public foo: {
  bar: number
} = {bar: 123};

//or

this.foo = {bar: 123};

Answer №2

To work around this issue, if foo has the potential to be undefined, you can define it as follows:

public foo: {
  bar: number
} | undefined;

By doing so, any errors will be caught at compile time (especially when using the --strictNullCheck option).

For more information on this matter, refer to the GitHub issue link provided by @Aleksey L.

Answer №3

Attempting to assign a value to the key bar on this.foo, but `this.foo` has not been initialized yet. To fix this, initialize it like so: this.foo = { bar: 123 };

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

Ways to dynamically eliminate focus around text inputs

I have created an HTML page and here is the link to it: https://i.sstatic.net/n8UdU.png My main goal is to remove the black border around the text input on this page. The challenge I am facing is that the 'things to do' list is generated dynamic ...

The error message "TypeError: Cannot set property 'href' of undefined" occurred at angular.js line 12520 when trying to set $window.location.href

Has anyone tried using a directive function to redirect when clicking with ng-click? Here is the HTML code: <a ng-click="navbarlinksCtrl.clickedfr()" ng-class="{active: clickedfr()}">FR</a><br> <a ng-click="navbarlinksCtrl.clickeden( ...

Tips for displaying only the items that are currently visible in an AngularJS Dropdown

I am currently working with an AngularJs object that looks like this: $scope.data = {'options': [{ "id": 1, "text": "Option 1", "isHidden": 0 }, { "id": 2, "text": "Option 2", "isHidden": 1 }, { "id": 3, "text": "Option 3", "isHidden": 0 }]}; U ...

Uploading a screenshot to a server using Ionic 4

I have encountered an issue while trying to take a screenshot and upload it to a server using the spring-boot. I utilized a native library for taking the screenshot and an Angular service to obtain the image URI. I converted the image URI to a blob and sen ...

What are the potential downsides of using ID to access HTML elements in React TypeScript?

During my previous job, I was advised against accessing HTML elements directly in React TypeScript using methods like getElementById. Currently, as I work on implementing Chart.js, I initially used a useRef hook for setting up the chart. However, it appear ...

Dealing with numerous dynamically generated tables while incorporating sorting in Angular: a comprehensive guide

I am faced with a challenge involving multiple dynamically created Angular tables, each containing the same columns but different data. The issue at hand is sorting the columns in each table separately. At present, I have two tables set up. On clicking the ...

Typescript is unable to access the global variables of Node.js

After using Typescript 1.8 with typings, I made the decision to upgrade to typescript 2.8 with @types. When I downloaded @types/node, my console started showing errors: error TS2304: Cannot find name 'require'. The project structure is as foll ...

How to tell if one mesh is contained within another in Three.js

Currently, I am experimenting with Three.js and trying to figure out a way to check if one mesh is completely contained within another mesh. I've created a small robot that moves around inside a home box controlled by the player. While I know how to d ...

Stop unauthorized pages from hijacking login cookies

I have a website called where users can create their own HTML pages accessible through the link if the username is "USR" and project is "PROJECT". However, there is a security concern... Currently, I store users' login tokens as cookies. But what ...

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

Can a universal type be designed for application across various types?

I've got this function: function stackPlayer(stack){ } The stack parameter can have one of the following forms only: a function that takes req, res, and next as arguments. a function that takes req, res, and next as arguments, and returns a functio ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

unable to retrieve the chosen item from the dropdown menu

How can I retrieve the value of the selected item from a dropdown menu without getting an undefined error? You can find my code on Jsfiddle. Can anyone spot what might be causing this issue? <select class="ddl_status" id="status_ddl_20" style="display ...

How do I dynamically incorporate Tinymce 4.x into a textarea?

I am encountering a small issue when trying to dynamically add tinymce to a textarea after initialization. tinymce.init({ selector: "textarea", theme: "modern", height: 100, plugins: [ "advlist autolink image lists charmap print p ...

What are the steps for integrating and expanding a JavaScript library using rollup, TypeScript, and Angular 2?

I am currently working on a project called angular2-google-maps-test and I am interested in integrating and expanding upon the JS library found at js-marker-clusterer npm install --save js-marker-clusterer It seems that this library is not structured as ...

Tips on utilizing Ajax for updating the RenderBody() segment

Can anyone help me understand why my Ajax.ActionLink menu item is calling JavaScript twice when I try to use it for the second time? I simply want to update the RenderBody() after clicking on a menu item. _Layout.cshtml: ... <body> <div i ...

Develop a web application in ASP.NET MVC 4 utilizing bundle configurations

At my workplace, we have an ASP.NET WebApp that utilizes ASP.NET MVC Bundles. To give you a clear picture, here is a snippet of the code: public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery ...

What is causing express.js not to authenticate properly?

I'm currently in the process of developing a server application using node.js, which is up and running on localhost:8080. As I attempt to make a login request, I've encountered an issue where one method works while the other fails. My suspicion i ...

Angular2 scripts are failing to load in the web browser

Setting up my index page has been more challenging than I anticipated. Take a look at my browser: https://i.stack.imgur.com/L4b6o.png Here is the index page I'm struggling with: https://i.stack.imgur.com/Op6lG.png I am completely stumped this tim ...

Skip creating declarations for certain files

src/ user.ts department.ts In the scenario outlined above, where there are two files in the src directory (user.ts and department.ts), is there a way to exclude the generation of declaration files specifically for department.ts when running tsc wi ...