What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this:

class Foo {
    public static bar() {
        console.log("test");
    }
}

The requirement was to call this TypeScript function from plain JavaScript located in a file named test.html:

<script src="test.js"></script>
<script>
    Foo.bar();
</script>

Both test.html and test.js exist in the same directory and are compiled and bundled by webpack. The task at hand was to make this interaction possible.

After making some modifications, my program now looks like this:

class Foo {
    public bar() {
        console.log("test");
    }
}

Despite these changes, the JavaScript code still fails to recognize the Foo class. Any suggestions on how to fix this issue would be greatly appreciated.

Answer №1

Here is the solution to your query:

In your test.ts:

class Foo {
    public static bar() {
        console.log("test");
    }
}
window.Foo = Foo;

In your test html:

<script src="test.js"></script>
<script>
    Foo.bar();
</script>

Your TypeScript compiler likely employs closure during compilation, encapsulating everything within the scope of an anonymous function:

(function(){
    ...
})()

To access your function from HTML, you must assign it to the window object.


If your tasks are simple, consider sticking to vanilla JavaScript instead of TypeScript. You can still use ES6 classes if needed.

TypeScript is better suited for more intricate solutions, where export/import mechanisms should be used between files instead of assigning to window...

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

Achieving perfect alignment of an iframe on a webpage

Having an issue with aligning the iframe on my website. I have two buttons set up as onclick events that connect to internal pages displaying PHP data in tables within the iframe. Despite trying various CSS styles and positioning methods, I can't seem ...

What is the process to transfer data from JavaScript to HTML within a Laravel environment?

I am attempting to transfer a value from JavaScript to HTML as a variable. In order to do this, I am retrieving the value from a Laravel PHP controller. JavaScript $("ul.nav-tabs > li > a").click(function() { var id = $(this).attr("href").repla ...

Navigating to Protected Mobile Platform

I am experiencing an issue with accessing a .NET website with SSL on my Blackberry device. When I try to view the site, I receive the message "HTTP ERROR 403 FORBIDDEN - You're not authorized to view this page. Please try loading a different page". Th ...

Unravel the JSON structure

Here is the JSON response I received from an AJAX call: [{"id":null,"period":null,"until":null,"agent_id":"15","agent_zlecajacy_id":"15","offer_id":null,"status":"1","tytul":"Pobranie ksi\u0105g","tresc":"Pobranie ksi\u0105g","data_aktualizacji" ...

What is the reason behind the triggering of actions by ngrx entity selectors?

I'm currently in the process of learning NgRx, but I'm struggling to comprehend why entity selectors would trigger actions. Despite my efforts to find an explanation, I have come up short. It's possible that I may be missing some fundamental ...

The functionality of JQuery ceases to function properly once the BxSlider plugin is activated

I've encountered a strange issue while using the BxSlider plugin of jQuery on my page. When I implement the code for the slider with BxSlider, all other custom functions seem to stop working without any errors being displayed in the console. I've ...

Navigating with Node.js and angular

I'm struggling with redirecting POST requests using Node.js, Express, and Angular. Typically, we'd use forms like this: index.ejs <!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <bo ...

Adjust the HTML content prior to displaying it to prevent any flickering

Is there a way to run code before the page is rendered, such as updating dates or converting text to HTML, without causing flickering when reloading multiple times? How can I ensure the code runs as it's drawn instead of waiting until the end to redra ...

Unable to retrieve Objects from JSON

Here is a JSON object I received: [{"model": "pricing.cashflow", "pk": 1, "fields": {"value": 4.0, "date": "2016-09-09"}}, {"model": "pricing.cashflow", "pk": 2, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 3, "fiel ...

What is the best way to set the active class on the initial tab that is determined dynamically rather than a static tab in Angular?

I'm currently facing a problem with ui-bootstrap's tabsets. I have one tab that is static (Other) and the rest are dynamically added using ng-repeat. The issue I'm having is that I can't seem to make the first dynamically loaded tab act ...

What is the best way to set up distinct Jest test environments for React Components and Backend API routes within NextJs?

In the realm of testing with NextJS, Jest comes into play effortlessly, complemented by React Testing Library for frontend testing. Interestingly, Jest can also be utilized to test backend code. Currently, I am incorporating a library in my API routes tha ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...

Using ES6 classes in Express routes: It is not possible to create the property 'next' on the string '/'

I'm currently working on integrating routes using classes in my express js application controller class User { constructor (){ this.username = 'me'; } getUsername(req,res){ res.json({ 'name& ...

Recursive React components. String iteration enhancement

In my React app, I am trying to create a string hierarchy from an object. The object structure is like this: { name: 'name1', parent:{ name: 'name2', parent:{ name: 'name3', parent: null }}} My plan is to use a state variable ...

Engaging User Forms for Enhanced Interactivity

I'm in the process of developing an application that involves filling out multiple forms in a sequential chain. Do you have any suggestions for creating a more efficient wizard or form system, aside from using bootstrap modals like I currently am? C ...

Encountering a ValueError when attempting to validate form fields with Django and JavaScript

I encountered an error while trying to validate a field using Javascript and Django. Error: ValueError at /insert/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/insert/ Django Version: ...

Submitting the object in the correct format for the Firebase database

My goal is to structure the Firebase database in the following way: "thumbnails": { "72": "http://url.to.72px.thumbnail", "144": "http://url.to.144px.thumbnail" } However, I am struggling to correctly set the keys '72' and '144&apos ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

Having trouble getting the form to submit with jQuery's submitHandler

I am in the process of converting a contact form to AJAX so that I can utilize the success function. Currently, I am encountering an issue where the code is halting at the submitHandler section due to it being undefined. Can anyone identify why my submitHa ...

Is it possible to make a form field inactive based on another input?

I need help with disabling certain form fields until other fields are filled in. You can check out an example of what I'm trying to achieve here: https://jsfiddle.net/fk8wLvbp/ <!-- Bootstrap docs: https://getbootstrap.com/docs --> <div ...