Is it possible to invoke JavaScript code from TypeScript?

I'm struggling with calling a JavaScript file from TypeScript. After resolving one import issue and adjusting the base function for tsc recognition, I'm now stuck on recognizing a declared function prototype in the JavaScript file.

Although I have set "allowJs": true.

This is what my fileTransfer.ts looks like:

import { XmlRpcRequest } from "./mimic";
const updateCommentBtn: HTMLButtonElement = document.getElementById(
    'makeComment',) as HTMLButtonElement;

updateCommentBtn.addEventListener('click', async () => {
    const method = "MakeComm";
    let request:any = XmlRpcRequest("http://localhost:1337/RPC2", method);
    request.addParam(document.getElementById("n1")).value;
    request.addParam(document.getElementById("n2")).value;
    let response = await request.send();
    console.log(response);
});

And here are the key parts of the mimic.js file that I am importing:

export const XmlRpcRequest = (url, method) => {
    this.serviceUrl = url;
    this.methodName = method;
    this.crossDomain = false;
    this.withCredentials = false;   
    this.params = [];
    this.headers = {};
};

XmlRpcRequest.prototype.addParam = (data) => {
    // Variables
    var type = typeof data;

    switch (type.toLowerCase()) {
        case "function":
            return;
        case "object":
            if (!data.constructor.name){
                return;
            }   
    }
    this.params.push(data);
};

The project compiles successfully with tsc and there are no linting errors. However, Chrome's console displays the following error:

mimic.js:8 Uncaught TypeError: Cannot set property 'addParam' of undefined

It seems like an issue with accessing the exported function's prototype, but I'm unsure how to resolve it. Worth mentioning, the file runs without any problems in a pure JavaScript environment; the issue only arises when transitioning to TypeScript.

Answer №1

Discover the reason why utilizing fat arrow syntax prevents access to the prototype:

Explore two additional explanations regarding the use of this with fat arrow syntax:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Use_of_prototype_property

To resolve this issue, it is recommended to define it using a standard function declaration:

const XmlRpcRequest = function(url, method) { ... }

Alternatively, consider utilizing the class syntax:

class XmlRpcRequest {
  constructor(url, method) {
    ...
  }
}

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

Is it possible to use node.js and express in an application to redirect a URL and eliminate a file extension from the previous website?

We are in the process of transitioning our website from an ASP environment hosted on a Windows server. The current URL is http://www.bruxzir.com/video-bruxzir-zirconia-dental-crown/index.aspx However, I would like it to be http://www.bruxzir.com/video ...

Utilize the Jest moduleNameMapper for locating files: "resolver": undefined

Among the various files I have, there is a text file located in the component directory within the path: src/components/text Despite this, Jest is unable to locate the file when utilizing the webpack alias import Text from "components/text"; I ...

Tips on accessing a browser cookie in a Next.js API endpoint

I've set a cookie in the layout.js component and it's visible in the browser. Now, I need to be able to retrieve that cookie value when a post request is made to my API and then perform some action based on that value. Despite trying different ...

CSS positioning with absolute value + determine the number of elements positioned above

Is it feasible to adjust the position of an absolutely positioned element based on the height of the element above it? The objective is to align elements with the class "pgafu-post-categories" one line above an H2 heading, even when the lengths v ...

Updates made in MobX store are not displaying in the web browser

Why are the data changes not reflecting in the view after the api call? Here is the code snippet that might help: store.js import axios from 'axios'; import {encrypt, decrypt} from '../utils/pgp.js' import {observable, action, compute ...

JavaScript code for displaying data sequentially one at a time

Hey there, I've developed a function that pulls data from a jsonp file. However, I'm looking to display this data one by one - starting with the vendor's name followed by their policyUrl. If you want to check out the source code, click on t ...

Creating a Node server exclusively for handling POST requests is a straightforward process

I'm looking to set up a Node server that specifically handles POST requests. The goal is to take the data from the request body and use it to make a system call. However, my current setup only includes: var express = require('express'); var ...

What is the best way to divide data prior to uploading it?

I am currently working on updating a function that sends data to a server, and I need to modify it so that it can upload the data in chunks. The original implementation of the function is as follows: private async updateDatasource(variableName: strin ...

Server Components can only receive plain objects and select built-ins from Client Components. Any classes or null prototypes will not be compatible

I am encountering an error when wrapping the App.ts with queryclientprovider: "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." Below is the code snippet from ...

A TypeScript interface or class

Just had a lively discussion with a coworker and wanted to get some clarification. When shaping an object in TS, should we use a class or an interface? If I need to ensure that a function returns an object of a specific type, which one is the best choice? ...

What is the best way to keep track of the most recent 100 items?

In Angular, I want to store the last 100 items to display. Currently, I am using an array and inserting items with 'array.push'. If this method is not effective for this scenario, what alternative approach can I take? Here is a snippet of the co ...

Error message: Cordova not found - unable to use 'ionic native' 3 for CRUD operations with SQLite database

I am attempting to manage CRUD data with SQLite in Ionic 3, but unfortunately cordova is not functioning as expected. https://i.sstatic.net/5m411.png ...

THREE.js: dual scenes sharing identical camera positions

I'm currently working on a project where I have two overlapping scenes. The top scene can be faded in and out using a slider, and users can rotate objects within the scene for a better view. My challenge is to keep the camera position consistent betw ...

Is your TypeScript spread functionality not functioning as expected?

I'm new to TypeScript, so please forgive me if I've made an error. On a guide about TypeScript that I found online, it states that the following TypeScript code is valid: function foo(x, y, z) { } var args = [0, 1, 2]; foo(...args); However, w ...

Ordering in D3 Code

I'm struggling with understanding the correct structure for writing D3 code. For example: In the code snippet below, I noticed that if I place the 3rd section (Chart Title) of the code after creating the svg element, the title text doesn't displ ...

Validation of emails in Angular through the utilization of reactive forms

Hello there, I'm new to Angular and looking for some assistance. Specifically, I am currently working on validating an email input using a reactive form with the keyup event. registerform:any; ngOnInit(): void { this.registerform = new F ...

Encountering compilation errors while using ng serve in NGCC

After attempting to update peer dependencies, I encountered an issue while compiling my Angular app. The error message displayed: Compiling @angular/material/core : es2015 as esm2015 Compiling @angular/material/expansion : es2015 as esm2015 Compiling @angu ...

Creating Layouts with Bootstrap 3

I'm exploring the codepen below in an attempt to mimic the appearance of the image provided consistently across all screen sizes. However, there are two issues that I am encountering - firstly, the green numbers on the first line which represent the d ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

Utilizing Element IDs for JQuery Tab Implementation

Having two buttons and two divs with paragraphs, I want to create tabs without adding new classes or IDs. Can I achieve tab switching using the existing IDs that end with "_one"? For instance: The first button has the ID "tab_button_one" and the first di ...