【问题标题】:How to Setup VS Code For Creating TypeScript Definition Files如何设置 VS Code 以创建 TypeScript 定义文件
【发布时间】:2017-05-21 08:46:36
【问题描述】:

我有这个当前的文件夹结构:

project
└───typings
│   |   index.d.ts
|   FileToMakeTdFor.js
|   FileToMakeTdFor-Tests.ts

我有一个 JS 文件,我正在尝试为其创建一个 Typescript 定义 (d.ts)。

js文件长这样:

"use strict";
var FileToMakeTdFor = (function () {
    function FileToMakeTdFor(config) {
        ...
    }
    FileToMakeTdFor.prototype.example = function () {
        ...
    };
    return CRMWebAPI;
}());
exports.FileToMakeTdFor = FileToMakeTdFor;

index.d.ts 文件如下所示:

export interface FileToMakeTdFor {
    new (config:any): FileToMakeTdFor;
    example(): void;
}

在我的测试文件中,我正在尝试这样写:

let obj = new FileToMakeTdFor();
obj.example();

但我在构造函数 Cannot find name FileToMakeTdFor 上遇到错误

如何让测试 ts 文件找到 index.d.ts 文件?有没有更好的方法来设置这个结构?

【问题讨论】:

  • 这有帮助吗:stackoverflow.com/a/39237584/1575281 这是 2.0.0 之前的版本
  • 如果代码和测试代码一起编译,则无需创建定义文件。它应该开箱即用。您的问题可能出在其他地方。
  • 另外,你是如何导入FileToMakeTdFor模块的?

标签: javascript typescript visual-studio-code


【解决方案1】:

特别感谢 Dave Hillier 的link。它把我带到了 TypeScript Handbook for declaration files。显然我只是错过了一些导出调用:

/*~ If this module is a UMD module that exposes a global variable 'CRMWebAPI' when
 *~ loaded outside a module loader environment, declare that global here.
 *~ Otherwise, delete this declaration.
 */
export as namespace FileToMakeTdFor;

/*~ This declaration specifies that the class constructor function
 *~ is the exported object from the file
 */
export = FileToMakeTdFor;

export interface FileToMakeTdFor {
    new (config:any): FileToMakeTdFor;
    example(): void;
}

一旦我添加了 export as namespace FileToMakeTdFor;export = FileToMakeTdFor; 行,一切都开始工作了......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2016-03-09
    • 1970-01-01
    • 2017-12-11
    • 2021-01-05
    • 2020-08-03
    • 2020-12-31
    • 2020-03-18
    相关资源
    最近更新 更多