【问题标题】:How to call JavaScript from TypeScript?如何从 TypeScript 调用 JavaScript?
【发布时间】:2019-01-08 20:38:08
【问题描述】:

我有一个想要从 typescript 调用的 javascript 文件。我修复了一个导入问题并修改了要在 tsc 中识别的基本函数,但是,我仍然面临识别 javascript 文件中声明的函数原型的问题。

我确实有"allowJs": true

这是我的文件Transfer.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);
});

这里是我要导入的mimic.js 文件的相关部分:

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 编译项目,linter 不会标记任何错误。但是,我在 Chrome 的控制台中收到以下错误:

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

在我看来,这似乎是访问导出函数原型的问题,但我不太确定如何解决它。我应该提一下,我可以在纯 Javascript 应用程序中很好地运行该文件,我只在进入 Typescript 环境时遇到这个问题。

【问题讨论】:

  • XmlRpcRequest 不返回任何内容。你需要用new调用它
  • 我试过了(我也需要新的 Javascript 版本),但是,当我输入 new XmlRpcRequest: 'new' 表达式时出现以下错误,其目标在 TypeScript 中缺少构造签名,隐式具有“任何”类型。
  • 考虑将其设为class,而不是原型类。
  • 旁注:typeof null === "object"
  • @Thomas 抱歉,我没有收到您对代码的引用?

标签: javascript typescript


【解决方案1】:

如果您想访问原型,以下是为什么您无法使用粗箭头语法的答案: https://teamtreehouse.com/community/does-arrow-function-syntax-works-for-prototype

这里有两个关于this的额外解释,带有粗箭头语法:

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

作为一种解决方案,您需要使用普通函数声明来定义它:

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

或者,您可以使用 class

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

【讨论】:

  • 你太棒了!是肥箭!
  • 如果其他人看到这个,我还需要添加:new (XmlRpcRequest as any)
猜你喜欢
  • 2017-06-23
  • 2012-09-24
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2018-09-06
  • 2017-12-18
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多