2

I am working with Angular and Meteor using Typescript. When I set up a collection I normally declare a global variable (that's the why meteor does it):

Invoices = new Mongo.Collection( 'invoices' );

Now I want to add the Invoices to my typescript custom definition so that code's intellisense doesn't trip over it. However, Invoices is part of window object and I can't duplicate a module declaration.

Just adding this to my custom.d.ts file works for intellisense in my code

var Invoices: Mongo.Collection<any>;

However code doesn't like the var. It says I need to use declare module. However, I can't redeclare module Window.

So I am a bit at a loss how to do it in a correct way.

2
  • declare var Invoices: Mongo.Collection<any>; seems to work. Is that the best way? Commented Feb 6, 2016 at 5:18
  • Please, convert this comment in an answer. It's the best one for TS 1.8+. In fact, I think this is the only one which works inside a module. Commented Apr 24, 2017 at 15:13

4 Answers 4

3

In addition to Zeeshan's answer, interfaces in TypeScript are self merging. One other way you can define this variable is to add it to the Window interface by using

interface Window{
    Invoices: Mongo.Collection<any>;
}

Which can then be used with

window.Invoices = /* your collection */;

One thing to note here is that window is required in the above example, where are using Zeeshan's proposal it is not. Which to use depends on your preference of how explicit you would like your code to be. I agree that using declare var can be more convenient, but it could also leave a developer searching for what scope that variable is defined.

I am simply proposing this as it could be a valuable alternative approach, depending on your preference of explicitness.

Sign up to request clarification or add additional context in comments.

Comments

2

Yeah go with declare var Invoices: Mongo.Collection<any>;

Good Tutorial for More Understanding

Happy Helping!

1 Comment

Zeeshan, with your edits you made a mistake. Code is Visual Studio Code, so not code :)
2

Make sure the interface name is Window (W -capital ) and in your declaration you need to define small window.

interface Window{
    Invoices: Mongo.Collection<any>;
}

// somewhere in class
private myvar = window.invoice

1 Comment

Does this need to be added to a type definition file? Like what's the best practice here?
0

One thing that seems to work fine is: declare var Invoices: Mongo.Collection<any>;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.