Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我应该如何在定义文件中定义全局TypeScript变量,以便导入它?_Javascript_Typescript_Typescript Typings - Fatal编程技术网

Javascript 我应该如何在定义文件中定义全局TypeScript变量,以便导入它?

Javascript 我应该如何在定义文件中定义全局TypeScript变量,以便导入它?,javascript,typescript,typescript-typings,Javascript,Typescript,Typescript Typings,我有一个带有全局参数的外部JS库: function Thing() { ... } ... var thing = new Thing(); 有一个TypeScript定义文件,因此在thing.d.ts中: declare var thing: ThingStatic; export default thing; export interface ThingStatic { functionOnThing(): ThingFoo; } export interface Th

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

function Thing() {  ...  }
...
var thing = new Thing();
有一个TypeScript定义文件,因此在
thing.d.ts
中:

declare var thing: ThingStatic;
export default thing;

export interface ThingStatic {
    functionOnThing(): ThingFoo;
}

export interface ThingFoo {
    ... and so on
然后我将其导入到我自己的TS文件中:

import thing from 'thing';
import {ThingFoo} from 'thing';
...
const x:ThingFoo = thing.functionOnThing();
问题是传送到:

const thing_1 = require("thing");
...
thing_1.default.functionOnThing();
这会抛出一个错误。我在中询问过这一点,建议使用:

import * as thing from 'thing';
这并不能解决它-它给了我TS中的
东西。默认值,但一旦传输到JS,它就没有定义

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


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

如果使用该库的唯一方法是访问其全局文件(而不是将其作为节点模块或amd或umd模块导入),然后,最简单的方法是在顶层创建一个声明文件,而不导出任何
s。仅仅声明一个变量就足够了。要使用它,您必须在编译typescript代码时包含该声明文件,方法是将其添加到
files
include
中的
tsconfig.json
,或直接在命令行上。您还必须在运行时使用
标记包含库

示例:thing.d.ts

declare var thing: ThingStatic;

declare interface ThingStatic {
    functionOnThing(): ThingFoo;
}

declare interface ThingFoo {
}
const x:ThingFoo = thing.functionOnThing();
测试东西。ts

declare var thing: ThingStatic;

declare interface ThingStatic {
    functionOnThing(): ThingFoo;
}

declare interface ThingFoo {
}
const x:ThingFoo = thing.functionOnThing();
可以一起编译

./node_modules/.bin/tsc test-thing.ts thing.d.ts
test thing.js中的结果:

var x = thing.functionOnThing();
另请参见关于环境声明


注意:有一些模块加载器允许像使用模块一样使用全局库,因此可以使用
import
语句而不是
标记,但如何配置这些模块加载器是另一个更复杂的问题。

这不起作用。如果没有
thing.d.ts中的
export
语句,那么
testthing.ts
就不知道全局变量
thing
是什么。环境声明可以工作,但首先就不能满足使用
thing.d.ts
的全部要求,因为现在一切都是
any
。这个全局变量是一个大型API的入口点-我希望定义对TypeScript可见。没有任何东西都是键入的,也没有
any
-为什么说“一切都是any”?。若它真的是一个全局变量,那个么就并没有办法导入它——你们不能导入并没有通过模块化javascript代码导出的东西。声明文件只是描述了javascript库中定义的现实,它不能改变它。这就是我尝试使用它时得到的结果。我开始认为这可能是VisualStudio中的一个bug。我将使用其他实现进行一些测试。尝试使用字符串名称声明-''declare var'thing'。我真的不明白为什么会这样,但我不得不在一个稍微不同的场景中做同样的事情。(在我的例子中,我从declare模块foo切换到declare模块‘foo’)