Error encountered during TypeScript execution - 'undefined'

I'm encountering errors while trying to instantiate a basic class named Point using HTML and TypeScript. Whenever I click on the hyperlink, I receive the following error messages within each try/catch block:

Errors:

  • Cannot read property 'Empty' of undefined.
  • undefined is not a function.
  • undefined is not a function.

HTML:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <script src="app.js"></script>
    <script type="text/javascript">
        function Test()
        {
            try { alert(MyLibrary.Point.Empty.ToString()); }
            catch (e) { alert(e.message); }

            try { alert(new MyLibrary.Point(10, 20).ToString()); }
            catch (e) { alert(e.message); }

            try { alert(MyLibrary.Point.FromPoint(new MyLibrary.Point(10, 20)).ToString()); }
            catch (e) { alert(e.message); }
        }
    </script>
</head>
<body>
    <a href="javascript:Test();">Click Me</a>
</body>
</html>

TypeScript:

module MyLibrary
{
    export interface IPoint { X: number; Y: number; ToString(): string; }

    export class Point implements MyLibrary.IPoint
    {
        private _X: number = 0;
        private _Y: number = 0;

        constructor(x: number, y: number)
        {
            this._X = x;
            this._Y = y;
        }

        public get X(): number { return (this._X); }
        public get Y(): number { return (this._Y); }

        public ToString(): string
        {
            return ("{" + this._X.toString() + "," + this._Y.toString() + "}");
        }

        public static FromPoint(point: MyLibrary.Point): MyLibrary.Point
        {
            return (new MyLibrary.Point(point.X, point.Y));
        }

        private static _Empty: MyLibrary.Point = new MyLibrary.Point(0, 0);
        public static get Empty(): MyLibrary.Point { return (MyLibrary.Point._Empty); }
    }
}

The TypeScript compiler works fine and the project adheres to ECMA5 standards. The issue seems to arise when utilizing static properties in the class. Any insights into why this might be happening? The generated JavaScript for the static properties is shown below:

Object.defineProperty(Point, "Empty", {
    get: function ()
    {
        return (MyLibrary.Point._Empty);
    },
    enumerable: true,
    configurable: true
});
Point._Empty = new MyLibrary.Point(0, 0);

Answer №1

During the initialization of a class's static members within a module, you cannot reference the qualified name of the class because it is not yet available by that name. Consider adjusting these two lines:

    private static _Empty: MyLibrary.Point = new MyLibrary.Point(0, 0);
    public static get Empty(): MyLibrary.Point { return (MyLibrary.Point._Empty); }

To this:

    private static _Empty: MyLibrary.Point = new Point(0, 0);
    public static get Empty(): MyLibrary.Point { return (Point._Empty); }

Upon reviewing the generated code, it becomes evident that the property MyLibrary.Point is only assigned after the static initialization of the class takes place. This behavior could be interpreted as a potential compiler flaw.

Answer №2

It appears that the module MyLibrary is being defined dynamically at runtime, but the class Point within it is not loading properly. This may be due to the JS file containing Point not being loaded.

If you are not utilizing modules, make sure to reference each JS file containing classes you wish to use at the top of your HTML file. Another option to consider is using the --out FILE compile option to consolidate all your classes into a single file for easier referencing.

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

The user authentication service indicates that no user is currently logged in

Currently, I am working on implementing a route guard to distinguish between authenticated users and guests. In order to achieve this, I have created an auth-guard service along with an auth service. Although the user data is successfully stored in the loc ...

What are the steps for integrating a date and time picker bootstrap plugin?

Referencing a tutorial from http://www.w3schools.com/bootstrap/bootstrap_modal.asp: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> <div id="myModal" class="modal fade" role= ...

Ignore one specific file when importing all files in Angular 7

In my Angular 7 project, I am utilizing C3 and importing all the necessary files at the beginning of my .ts component file using a wildcard. import * as c3 from 'c3'; While this method works well overall, I encountered an issue where my CSS ove ...

jQuery toggle functioning in one scenario, but failing in another

My experience with JS/Jquery is limited which might explain why I'm struggling with this. I am attempting to hide some text on a page and then make it visible again by clicking on a toggle link. The JavaScript code below is what I have been using. The ...

The error message from Object.create() indicates that the argument provided is not recognized as

Description Within my project, I am handling a JSON file, parsing it into an object, and attempting to transform it into an instance of the ProjectFile class using Object.create(). Code let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf- ...

Display a loading animation before the page loads upon clicking

$("#button").click(function(){ $(document).ready(function() { $('#wrapper').load('page.php'); }); }); <div id="wrapper"></div> <div id="button">click me</div> I would like to display a loading ic ...

Comparing numbers in Angular using Typescript

Hello! I'm encountering an issue with comparing two variables: console.log(simulation.population == 40000000); //true console.log(simulation.initialInfectedNumber == 5); //true console.log(simulation.population < simulation.initialInfectedNumber); ...

Ways to Halt observable.timer in Angular 2

As I work on Angular2's Component, I am currently implementing the following functions: export class MypageEditComponent { ngOnInit() { this.timer = Observable.timer(100, 100); this.timer.subscribe(t => { this.setFormData(); } ...

Querying Parse Server for objectId information

Within my web app that utilizes the Parse Server Javascript SDK, I have implemented the following query. While the console log accurately displays the retrieved information, the objectId field appears as "undefined." var query = new Parse.Query("myClass") ...

Is it possible to have more than one button for each item on my Shopping List App?

I am developing a shopping list app that allows users to add items to a list. Each item added triggers the display of a button next to it, enabling users to remove the item from the list when needed. However, a problem arises as more items are added – i ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Exploring the Benefits of Google Sitemap Integration with .NET 1.1

How can one efficiently generate a sitemap for Google using .NET 1.1 and then incorporate this sitemap into a treeview on a webpage with the .aspx extension? ...

Tips for maintaining i18n locale slugs and ensuring i18n consistency when reloading in Next.js

I'm currently utilizing next-translate. The default recognition of my routes is as follows: /about <--- /de/about /es/about However, I would like to set a specific locale for all paths: /en/about <--- /de/about /es/about Below is ...

Inject Custom ASP Control Script into the DOM dynamically upon registration

During a postback, I am loading my ascx control when a dropdown change event occurs. Parent C#: private void ddlChange() { MyControl myCtr = (CallScript)Page.LoadControl("~/Controls/MyControl.ascx"); myCtr.property = "something"; // setting publ ...

Data that is loaded asynchronously will not display rendered

I have async data loading via jayson from a server. After the data has finished loading, the boolean "loading" is set to false but my content does not re-render. Even though I can see on the console that the data was loaded correctly. var App = new Vue( ...

Preventing context menu from appearing on a right click by implementing a trigger to re-enable it

I am looking to implement a functionality on my website that disables the right click menu. Currently, I have achieved this through the following code: document.addEventListener("contextmenu", function(e){e.preventDefault(); }, false); Now, I am wonderin ...

Koa and Stripe are patiently holding off on displaying the page

My current setup involves using koa and stripe for processing a one-time payment. Although the functionality is there, I'm facing an issue where the page renders before the 'data' assignment takes place. This results in the 'id' sh ...

Attempting to replace an AngularJS object with another service results in it being reinitialized upon using ctrl + f5 in the application

In my AngularJS application, I have two services. One service is used to declare objects with default values, while the other service is responsible for assigning new values to those objects. Everything works fine in the controllers after rewriting, but wh ...

Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try. Here is my initial attempt: var input = document.getElementById( ...

Steps to retrieve the ID after modifying the owl carousel orientation

How can I retrieve the current id after switching sides in a slider? Currently, it only shows the previous id when there is a change. JavaScript Solution: hometopowl.on('changed.owl.carousel', function(event) { var activeMenu = $(".body-top-sli ...