Reputation: 6742
I know exposing a global variable is not a good practice, but in my case its necessary. I have another applications on a web-page alongside my angular one and those must access one globally exposed variable.
My question is, how to expose a variable inside angular?
When I'm appending it to document
like this: document.test = "Hello";
, the TypeScript throws an error Property 'test' does not exist on type 'Document'.
Is there an another way of doing this?
Upvotes: 0
Views: 1454
Reputation: 8470
In a general sense, yeah you would not want to do that if you just have an Angular app. To answer your question tho so that you can get the other part of your app to work, did you try to use a declare statement at the top of your file to prevent TypeScript from complaining?
// import statements
declare var document;
http://blogs.microsoft.co.il/gilf/2013/07/22/quick-tip-typescript-declare-keyword/
Additionally, you can have the TypeScript compiler treat a known variable as the any
type so you can use whatever properties you want on it that it may not know about. To do this, you simply cast the variable using the as
syntax. It is better to use TypeScript's type checking, but you can opt out of it by doing this.
(document as any).foo = 'bar';
You should also be able to create an interface for these global properties and cast the document as that type to make use of TypeScript's type safety in your Angular code.
interface GlobalDocumentProps {
foo: string;
}
(document as GlobalDocumentProps).foo = 'bar';
Upvotes: 1