在我的Angular应用程序中,我可以通过安装包@types/Angular来访问Angular类型。然后,在我的TS文件中,我可以执行timeout: ng.ITimeoutService
之类的操作,而不必将任何内容导入到我的文件中。然后我可以运行tsc
,一切都编译得很好。VSCode也没有抱怨它找不到ng.ITimeoutService
。
然而,当我尝试用自己的自定义类型来模拟这种行为时,如果不在文件中显式导入模块,它就无法工作。我在做什么:
-
创建包含以下内容的文件
vendor/@types/custom/index.d.ts
:export declare class MyClass {...}
-
在我的tsconfig.json中,我将此路径添加到typeRoots:
"typeRoots": ["./vendor/@types/custom"]
现在在我的应用程序文件中/app/view.ts,我尝试这样做:
public myObject: MyClass
然而,VSCode和tsc抱怨道:
找不到名称"MyClass">
我甚至尝试过使用引用:
/// <reference path="../vendor/@types/custom/index.d.ts" />
但这给出了相同的结果。
如何访问类型而不导入其文件,类似于如何访问node_modules/@types中的类型而不必导入它们?
您可能需要查看全局定义。我敢肯定像angular这样的库就是这样做ng.ITimeoutService
的。但是,您可能需要有自己的命名空间,如下所示。
/*~ If your library has properties exposed on a global variable,
*~ place them here.
*~ You should also place types (interfaces and type alias) here.
*/
declare namespace myLib {
//~ We can write 'myLib.timeout = 50;'
let timeout: number;
}
编辑
似乎可以在types.d.ts
文件中添加一个global
类。我在VSCode中使用typescript 3.8.3
。
这是我的types.d.ts
// This is accesible anywhere now
declare class Aaaaa {
myFunction();
}
这是我的tsconfig.json
{
"compilerOptions": {
"outDir": "dist",
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"lib": ["es6", "es2016", "dom"],
"baseUrl": "src",
"preserveConstEnums": true,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"typeRoots": ["node_modules/@types", "src/types.d.ts"]
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
警告:全局类型不是一个好主意(应该是最后的选择(。此外,全局类上不能有任何初始化程序,因此必须在其他地方全局加载实现(通常通过浏览器中的脚本标记(。