[英]How to express a browser window property as a specific type in Typescript
In my Angular app's index.html, there is a script tag that includes a JavaScript file with 3rd party code that will attach a global property to the window object when the page loads.在我的 Angular 应用程序的 index.html 中,有一个脚本标记,其中包含一个带有 3rd 方代码的 JavaScript 文件,该文件将在页面加载时将全局属性附加到 window 对象。
I want to reference this property as a strongly-typed module within an Angular service.我想将此属性引用为 Angular 服务中的强类型模块。
I can get access to the property like so.我可以像这样访问该属性。
const foo: any = (window as any).foo;
However, the variable is of type "any" and I would like to express it as a specific type, "foo".但是,该变量的类型为“any”,我想将其表示为特定类型“foo”。
I have a "foo" typings file which I have placed in the following path within the Angular project.我有一个“foo”typings 文件,我已将其放置在 Angular 项目中的以下路径中。
src/@types/foo/index.d.ts
I modified the tsconfig.json to include the @types location.我修改了 tsconfig.json 以包含 @types 位置。
"typeRoots": [
"node_modules/@types",
"src/@types"
],
The typings file exports a foo
module like so:打字文件导出一个foo
模块,如下所示:
declare module 'foo' { /* etc. */ }
It is at this point that I am stuck.正是在这一点上,我被困住了。 I must be thinking about it wrong, because I can't find any examples of this situation.我一定是想错了,因为我找不到这种情况的任何例子。
I tried using /// <reference path="../../@types/foo/index.d.ts" />
to pull the type definition into service, but I am not sure what that buys me.我尝试使用/// <reference path="../../@types/foo/index.d.ts" />
将类型定义拉入服务,但我不确定这对我有什么好处。
I tried creating a separate module that exports the foo module like this export const foo = (window as any).foo;
我尝试创建一个单独的模块来导出 foo 模块,就像这样export const foo = (window as any).foo;
, but Typescript doesn't detect the connection between it and the typings file. ,但 Typescript 没有检测到它和typings 文件之间的连接。
I tried renaming the variable so that it would look like this const baz: foo = (window as any).foo;
我尝试重命名变量,使其看起来像这样const baz: foo = (window as any).foo;
, but it doesn't work. ,但它不起作用。
EDIT: 2019-12-05 Here's what I ultimately put in my Angular service.编辑: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;
You can just cast it twice to the correct type.您可以将它两次转换为正确的类型。
type WindowWithFoo = Window & { foo: SomeSpecificType};
(window as any as WindowWithFoo).foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.