我应该如何在定义文件中定义全局 TypeScript 变量以便可以导入? [英] How should I define a global TypeScript variable in a definition file so that it can be imported?

查看:21
本文介绍了我应该如何在定义文件中定义全局 TypeScript 变量以便可以导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有全局参数的外部 JS 库:

I have an external JS library with a global parameter:

function Thing() {  ...  }
...
var thing = new Thing();

有一个TypeScript定义文件,所以在thing.d.ts中:

There is a TypeScript definition file, so in thing.d.ts:

declare var thing: ThingStatic;
export default thing;

export interface ThingStatic {
    functionOnThing(): ThingFoo;
}

export interface ThingFoo {
    ... and so on

然后我将其导入到我自己的 TS 文件中:

Then I import this into my own TS files with:

import thing from 'thing';
import {ThingFoo} from 'thing';
...
const x:ThingFoo = thing.functionOnThing();

问题是转译为:

const thing_1 = require("thing");
...
thing_1.default.functionOnThing();

这会引发错误.我在另一个问题中问过这个问题,建议使用:

Which throws an error. I've asked about that in another question, and the suggestion is to use:

import * as thing from 'thing';

这并没有解决它 - 它在 TS 中给了我 thing.default 但是一旦转换为 JS 就未定义.

That doesn't fix it - it gives me thing.default in TS but then that's undefined once transpiled to JS.

我认为 thing.d.ts 有问题 - 必须有一种方法来定义可以导入的类型化全局参数.

I think there's something wrong with thing.d.ts - there must be a way to define a typed global parameter that can be imported.

我应该如何编写 thing.d.ts 以便它正确地表示 JS 并且不会转换为包含 default 或其他实际上不存在的属性?

How should I write thing.d.ts so that it represents the JS correctly and doesn't transpile to include default or other properties not actually present?

推荐答案

如果使用该库的唯一方法是访问其全局变量(而不是将其作为 node 模块或 amd 或 umd 模块导入),那么最简单的方法要走的是在顶层没有任何 export 的声明文件.只需声明一个变量就足够了.要使用它,您必须在编译打字稿代码时包含该声明文件,方法是将其添加到 filesinclude 中的 tsconfig.json,或直接在命令行上.您还必须在运行时使用

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆