Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Add functions to "window" with ".d.ts" File

Tags:

typescript

I'm having a legacy *.js application and want to port parts of it to typescript.

So far I found @types definitions for most of the used packages, but there is a global function added to the window object.

I was able to fix the compilation error by addind this at the beginning of the *.ts File:

declare global {
    interface Window {
        openConformationModal?: any;
    }
}

Now obv I don't want to include this in all my *.ts so I wanted to added it to a *.d.ts file so it is recogniced in all packages.

The problem is, that if I add the same file to a e.g. window.d.ts file, it isn't recogniced. I know that the types in the folder are found because I a added it with

 {
  ...,
  "compilerOptions": {
    ....
    "typeRoots": [
      "FFOLDERPATH_TO_D_TS_FILE"
    ]
  }
}

and there is another *.d.ts which is found.

PS: Solution is based on How do you explicitly set a new property on `window` in TypeScript?

like image 363
Stefan Avatar asked May 23 '18 12:05

Stefan


People also ask

How do I add a property to the windows in TypeScript?

To extend the window type in TypeScript, create a . d. ts file where you extend the Window interface adding the names and types of the properties you intend to access on the window object.

What is D TS in TypeScript?

The "d. ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.


1 Answers

I found it further down this question: https://stackoverflow.com/a/40698148

interface Window {
  MyNamespace: any;
}

Full answer:

Here's how to do it, if you're using TypeScript Definition Manager!

npm install typings --global

Create typings/custom/window.d.ts:

interface Window {
  MyNamespace: any;
}

declare var window: Window;

Install your custom typing:

typings install file:typings/custom/window.d.ts --save --global

Done, use it‌! Typescript won't complain anymore:

window.MyNamespace = window.MyNamespace || {};
like image 138
Stefan Avatar answered Oct 12 '22 03:10

Stefan