我应该如何在定义文件中定义全局 TypeScript 变量以便可以导入? [英] How should I define a global TypeScript variable in a definition file so that it can be imported?
问题描述
我有一个带有全局参数的外部 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
的声明文件.只需声明一个变量就足够了.要使用它,您必须在编译打字稿代码时包含该声明文件,方法是将其添加到 files
或 include
中的 tsconfig.json
,或直接在命令行上.您还必须在运行时使用 标签包含库.
If the only way to use that library is by accessing its globals (as opposed to importing it as node module or amd or umd module), then the easiest way to go is have a declaration file without any export
s at top level. Just declaring a variable is enough. To use it, you have to include that declaration file when compiling your typescript code, either by adding it to files
or include
in tsconfig.json
, or directly on command line. You also have to include the library with a <script>
tag at runtime.
示例:thing.d.ts
declare var thing: ThingStatic;
declare interface ThingStatic {
functionOnThing(): ThingFoo;
}
declare interface ThingFoo {
}
test-thing.ts
const x:ThingFoo = thing.functionOnThing();
可以一起编译
./node_modules/.bin/tsc test-thing.ts thing.d.ts
test-thing.js
中的结果:
var x = thing.functionOnThing();
另见关于环境声明的这个问题.
注意:有一些模块加载器允许像使用模块一样使用全局库,所以可以使用 import
语句而不是 标记,但如何配置这些模块加载器来做到这一点是另一个更复杂的问题.
Note: there are module loaders out there that allow using global libraries as if they were modules, so it's possible to use import
statement instead of <script>
tag, but how to configure these module loaders to do that is another, more complicated question.
这篇关于我应该如何在定义文件中定义全局 TypeScript 变量以便可以导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!