简体   繁体   中英

How to call JavaScript from TypeScript?

I have a javascript file that I want to call from typescript. I fixed one import problem and modified the base function to be recognized in tsc, however, I'm still facing an issue recognizing a declared function prototype in the javascript file.

I do have "allowJs": true .

Here is my fileTransfer.ts:

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 relevant portions of the mimic.js file that I'm 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) => {
    // Vars
    var type = typeof data;

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

tsc compiles the project and the linter does not flag any errors. But, I get the following error in Chrome's console:

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

This seems to me like an issue with accessing the exported function's prototype but I'm not quite sure how to fix it. I should mention that I can run the file just fine in a Javascript only application, I only face this issue going to the Typescript environment.

Here's an answer why you're unable to use fat arrow syntax if you want to access prototype: https://teamtreehouse.com/community/does-arrow-function-syntax-works-for-prototype

Here's two additional explanations about 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

As a resolution you need to define it with normal function declaration:

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

Alternatively, you could use class :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM