【问题标题】:Typescript not recognizing constructor of an un-typed node module打字稿无法识别无类型节点模块的构造函数
【发布时间】:2019-11-12 20:49:59
【问题描述】:

这是我第一次用 TypeScript 和 JavaScript 编写代码。我现在面临一个问题,我需要使用一个相当老的 Node Module。我是这样导入的:

import * as D2L from 'valence/lib/valence'

当我尝试使用它时:

let appContext = new D2L.ApplicationContext('asd', 'asd').createUrlForAuthentication('wlutest.brightspace.com', 443, 'localhost:8100/callback');

弹出这个错误:

ERROR TypeError: _valenceES6__WEBPACK_IMPORTED_MODULE_8__.ApplicationContext 不是构造函数

我已经尝试为这个模块生成 d.ts,但唯一的效果似乎是让我的 IDE 平静下来,但错误仍然存​​在。 我以前没有使用 JavaScript 的经验,但从 valence.js 的第 193 行开始对我来说似乎是一个合适的构造函数:

/**
 * Build a new ApplicationContext instance.
 *
 * An application context stores the state of the application (app ID, and app
 * Key) and provides methods for authentication. Given the authentication
 * information, it creates a {@link D2L.UserContext} with the appropriate
 * arguments.
 *
 * @param {String} appId Application ID as provided by Desire2Learn's key tool.
 * @param {String} appKey Application Key as provided by Desire2Learn's key tool.
 *
 * @constructor
 * @this {D2L.ApplicationContext}
 */
D2L.ApplicationContext =
    function (appId, appKey) {
        // Previous version took an appUrl as a first argument but threw it
        // away. This provides backwards compatibility for that contract.
        if (arguments.length === 3) {
            appId = arguments[1];
            appKey = arguments[2];
        }

        this.appId = appId;
        this.appKey = appKey;
    };

我还尝试使用工具将此文件转换为其他 js 版本,但没有成功。有人可以对此有所了解吗?

【问题讨论】:

  • 试试let appContext = D2L.ApplicationContext('asd', 'asd') 不带new
  • @Dimanoid 当我删除new 我得到ERROR TypeError: _valenceES6__WEBPACK_IMPORTED_MODULE_8__.ApplicationContext is not a function 这是正常的和好的。因为不应直接调用类原型。但是编译通过了,所以它知道 ApplicationContext 存在。
  • 您的 TS 配置是否启用了 allowSyntheticDefaultImports?

标签: javascript typescript node-modules


【解决方案1】:

原来我使用的模块已经过时了,它甚至在 JS 文件的末尾都没有module.exports = ...。添加后,我的项目现在可以识别该库了。

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多