Having trouble creating instances of a TypeScript class in JavaScript

I apologize for the potentially problematic inquiry.

Issue:

Here is the TypeScript class definition:

1    class MyClass {
2        constructor() {
3            alert("MyClass instantiated!");
4        }
5    }
6    export = MyClass;

After compilation, it becomes JavaScript like this:

1    var MyClass = (function () {
2        function MyClass() {
3            var _this = this;
4            alert("MyClass instantiated!"); 
5        }
6    }
7    module.exports = MyClass

The class is referenced in a JSP page that contains this script:

<script language='javascript' src="myclass.js">
    var myclass = new MyClass();
</script>

Upon debugging, it's observed that the code reaches line 1 of the compiled JavaScript file but exits at line number 7.

Inquiry:

Why does the execution not enter the function and rather exits? Could there be an issue with how I'm instantiating it?

Answer №1

The issue arises from your export of TypeScript in a commonjs format (as shown by the presence of module.exports = MyClass at line 7). To resolve this, you must compile the TypeScript into a format compatible with the browser, such as UMD. Alternatively, you can simply delete export = MyClass; from the TypeScript source.


Here is an example of functional TS code:

class MyClass {
    constructor() {
        alert("MyClass has been instantiated!");
    }
}

Upon compilation, it will look like this:

var MyClass = (function () {
    function MyClass() {
        var _this = this;
        alert("MyClass instantiated!"); 
    }
}

To use it on a webpage, follow these steps:

<script type="text/javascript" src="myclass.js"></script>
<script>
    var myclass = new MyClass();
</script>

Answer №2

It is not possible to include context within a script tag that is fetching another file.

Here's an alternative approach:

<script src="myclass.js"></script>
<script>
    var myclass = new MyClass();
</script>

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

Triggering a 'RegisterStartupScript' call resulted in an 'Object expected' error

Something strange is happening here. Let me explain the situation: I have a page with a usercontrol used for popups. This usercontrol has a placeholder where I can load any other usercontrol dynamically inside the popup. Everything works smoothly thanks ...

The inline style fails to take effect on input elements that are generated dynamically

Consider: $( "#scanInDialogItems tr td:nth-child( 3 )").mouseenter( function() { var q = $( this ).html(); $( this ).html( "<input type='number' style='text-align:right width:50px' min='1' value='" + q + " ...

Looping through elements using .each in jQuery and accessing their values in the following iteration

Here is the code snippet I've been working on: var index=0; var load=0; $("td.load_ads").each(function(){ var loading=$(this); $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id' ...

Validating American phone numbers using regular expressions

I came across a Javascript regex that is used to validate the different formats in which US phone numbers can be written. However, there seems to be an issue with it: it fails to match the second rule within this specific group: The first group of three ...

Updating the jQuery AJAX URL dynamically based on user input in a form submission

Exploring the world of AJAX and form submission, I find myself in need of assistance. My webpage is designed to display real-time stock market data, updating fields with the latest price, change, high, low, and more. I am currently attempting to modify th ...

AngularJS: Display the last four characters of a string and substitute the rest with 'X'

I am attempting to change the characters with X and make it look something like this XXXXXT123 This is what I have tried: var sno = 'TEST123'; alert(sno.slice(0,3).replaceWith('X')); However, I encountered an error in the console ...

What could be the reason for THREE.ColladaLoader causing a complete suspension of all operations on the website

While attempting to load an animated .dae file, I utilized the 'onProgress' argument to track its loading progress. Surprisingly, the file reaches 74% loaded in just 2 seconds, only to have the entire page freeze for an additional 23 seconds befo ...

Updating input value in Vue using JavaScript method

When using JavaScript to set the value of an input in my Vue method, it initially appears to work. However, when I try to save the data, it only saves what was typed before the value was updated by the method. For example, if I type new yor and select "New ...

Exploring methods to iterate through individual models in an array within an Angular Component

I am in need of calling a web service by providing inputs and using POST method. The response from the service will be a JSON array consisting of objects. My goal is to gather these objects into an Angular Array of Objects and present them on the webpage. ...

When a timeout is triggered, the AngularJS Promise is not being cancelled

In my endeavor to incorporate a simple timeout feature into my promise, I set out with the intention that if I do not receive a response within 1 second, the request should be terminated. The code should not hang for a response nor execute any code intende ...

The presence of onChange?: (ValueType, ActionMeta) => void with OptionType is not compatible

After updating to version v2.4.2, I keep encountering an error from flow regarding react-select. It seems that I am passing the correct types to the handle change, which expects an array with objects + OptionType accepting any string [string]: any. Can som ...

Is there a way to set up one function that can be used across different HTML buttons?

As a newcomer to JS, I've taken on the challenge of creating a size comparison tool for practice. In my HTML file, I have multiple buttons representing different US sizes that should display the corresponding UK, EU, and CM size when clicked inside a ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

A guide on inserting multiple values into a database table using PHP

Can you please take a look at this jsfiddle? Here are my results, http://jsfiddle.net/kz1vfnx2/ I am looking to store this data into a SQL Server database, one by one in each row using PHP Codeigniter. The insert table should look like this: Date ...

Cosmic Plantation Matrix Classification Or Arrangement

I am currently utilizing angular 9 along with Nebular v6.1.0 in my project. One issue I have encountered is related to filtering and sorting data displayed using the nebular TreeGridComponent. When dealing with basic data types such as strings or numbers, ...

How can the session user object be modified after logging in?

I've encountered a strange issue and I'm puzzled about its origin. In my Next.js app, I make use of the next-auth library to implement the authentication system. Initially, everything seems fine - I can successfully sign in by verifying the cred ...

Steps for creating a file selection feature in Chonky.js

I recently integrated the Chonky library into my application to build a file explorer feature. One challenge I am facing is figuring out how to select a file and retrieve its unique ID when the user double clicks on it. const [files, setFiles] ...

I'm trying to speed up my loop because it's currently running way too slow. Any suggestions

In an attempt to find the index of the maximum element after left rotation, I have come up with a method. The idea is to rotate array 'a' based on another array called 'rotate'. Each element in the 'rotate' array determines ho ...

Ensuring the website retains the user's chosen theme upon reloading

I have been developing a ToDo App using MongoDB, EJS, and Node JS. My current challenge involves implementing a theme changer button that successfully changes colors when clicked. However, whenever a new item is added to the database, the page reloads caus ...

What could be the reason for the electron defaultPath failing to open the specified directory?

Hi, I'm experiencing difficulties opening the directory path (/home/userxyz/Releases/alpha) using electron. This is what I have attempted: I have a similar path on Ubuntu: /home/userxyz/Releases/alpha When trying to access this path with the fo ...