使用 Angular 8 和 TypeScript 3.4.5 编写应用程序。
使用
ng server
运行本地 Angular 开发服务器时,出现阻止编译的错误:
ERROR in src/app/providers.ts:152:36 - error TS2339: Property 'API' does not exist on type 'Window'.
152 { provide: API, useValue: window.API },
~~~
src/environments/environment.static.ts:18:8 - error TS2339: Property 'FooServices' does not exist on type 'Window'.
18 parent.FooServices.Component = (): { subscribe: () => void } => {
~~~~~~~~~~~~~~
src/zone-flags.ts:1:8 - error TS2339: Property '__Zone_disable_requestAnimationFrame' does not exist on type 'Window'.
1 window.__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
我发现,是为标准浏览器的
Window
对象创建自定义全局类型扩展。
所以我制作了自定义全局类型:
declare global {
interface Date {
format(value: string): string;
}
interface Window {
__Zone_disable_on_property: any;
__Zone_disable_requestAnimationFrame: any;
__Zone_disable_XHR: any;
__Zone_ignore_on_properties: any;
__zone_symbol__BLACK_LISTED_EVENTS: any;
API: any;
BUS: any;
bus: any;
config: any;
ContentConfig: any;
ContentManager: any;
ContentQueue: any;
DataRegistry: any;
global: any;
hostMessageSender: any;
LanguageUtils: any;
lock: any;
logger: any;
mdiManager: any;
METER: any;
msg: any;
FooServices: any;
FooConfig: any;
RegistryUtils: any;
serviceMenuController: any;
XMLHttpRequest: any;
}
}
export {};
这是我的
tsconfig.json
文件:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"downlevelIteration": true,
"outDir": "./dist/out-tsc",
"sourceMap": false,
"declaration": false,
"module": "amd",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"noImplicitAny": false,
"typeRoots": [
"projects/shared/src/lib/types",
"node_modules/@types"
],
"lib": ["es2018", "dom"],
"resolveJsonModule": true
}
}
理论上这个配置应该可以工作,因为
user_interface/projects/shared/src/lib/types/global.d.ts
文件中的自定义类型已正确包含在上面的配置中。
但我的 IntelliJ IDEA Ultimate 仍然不断指出某些使用
parent.FooServices
或 window.FooConfig
等对象的文件中的类型错误。
根据这篇短文如何在 TypeScript 中声明全局类型,这个解决方案应该可以正常工作。
我真的不知道我错过了什么以及我在哪里算错了。
我通过SO看到的是,很多人时不时地在自定义类型方面遇到同样的问题。