在我的Angular应用程序的index.html中,有一个脚本标签,其中包含带有第3方代码的JavaScript文件,该文件将在页面加载时将全局属性附加到窗口对象上。
我想将此属性作为Angular服务中的强类型模块引用。
我可以像这样访问属性。
const foo: any = (window as any).foo;
但是,变量的类型为“ any”,我想将其表示为特定类型的“ foo”。
我有一个“ foo”类型文件,该文件已放在Angular项目的以下路径中。
src/@types/foo/index.d.ts
我修改了tsconfig.json以包含@types位置。
"typeRoots": [
"node_modules/@types",
"src/@types"
],
键入文件将导出foo
模块,如下所示:
declare module 'foo' { /* etc. */ }
在这一点上我被困住了。我一定在想错了,因为找不到这种情况的任何例子。
我尝试使用/// <reference path="../../@types/foo/index.d.ts" />
将类型定义引入服务,但是我不确定是什么买了我。
我尝试创建一个单独的模块来导出foo模块,例如export const foo = (window as any).foo;
,但是Typescript不会检测到它与类型文件之间的连接。
我尝试重命名该变量,以使其看起来像const baz: foo = (window as any).foo;
,但它不起作用。
编辑:2019-12-05 这就是我最终在Angular服务中放的内容。
import * as foons from 'foo'; //foo namespace
type WindowWithFoo = Window & { foo: typeof foons};
const foo = (window as any as WindowWithFoo).foo;
答案 0 :(得分:0)
您只需将其转换为正确的类型两次即可。
type WindowWithFoo = Window & { foo: SomeSpecificType};
(window as any as WindowWithFoo).foo