【问题标题】:How to properly declare a typescript global type of a given module for ts-check?如何为 ts-check 正确声明给定模块的 typescript 全局类型?
【发布时间】:2017-11-11 10:42:49
【问题描述】:

我有一个带有定义文件的模块 Xpto 的图像:

// node_modules/@types/xpto.d.ts
export interface Vertx {
  createHttpServer(handler: () => void) : void;
}

并声明一个助手来跟踪我的全局变量:

// runtime.d.ts
import {Xpto} from 'xpto';

declare const xpto: Xpto;

最后在我的 JS 文件上:

/// <reference path="runtime.d.ts" />
// @ts-check

xpto.createHttpServer(function (req) { ... }); 

由于某种原因,我在 vscode 上遇到错误:Cannot find name "xpto",但如果我导入类型就会起作用:

import {xpto} from "runtime"

但是这会生成损坏的代码,因为没有真正的运行时模块,这只是我声明哪些变量在全局范围内可用的一种方式。

【问题讨论】:

    标签: visual-studio-code typescript-typings


    【解决方案1】:

    我认为问题在于importexportd.ts 文件变成了模块声明。这就是为什么全局版本不起作用但带有import 的版本起作用的原因。

    尝试使用declare globalxpto 明确声明为全局变量:

    import {Xpto} from 'xpto';
    
    declare global { 
        declare const xpto: Xpto;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 2019-03-08
      • 2019-01-04
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      相关资源
      最近更新 更多