jedatu
jedatu

Reputation: 4123

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.

I want to reference this property as a strongly-typed module within an Angular service.

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".

I have a "foo" typings file which I have placed in the following path within the Angular project.

src/@types/foo/index.d.ts

I modified the tsconfig.json to include the @types location.

  "typeRoots": [
    "node_modules/@types",
    "src/@types"
  ],

The typings file exports a foo module like so:

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.

I tried creating a separate module that exports the foo module like this export const foo = (window as any).foo;, but Typescript doesn't detect the connection between it and the typings file.

I tried renaming the variable so that it would look like this 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.

import * as foons from 'foo'; //foo namespace
type WindowWithFoo = Window & { foo: typeof foons};
const foo = (window as any as WindowWithFoo).foo;

Upvotes: 1

Views: 1356

Answers (1)

pascalpuetz
pascalpuetz

Reputation: 5418

You can just cast it twice to the correct type.

type WindowWithFoo = Window & { foo: SomeSpecificType};
(window as any as WindowWithFoo).foo

Upvotes: 1

Related Questions