Reputation: 469
i have a service worker and it can't find a global variable. i'm not sure why, can someone explain why it doen't see global variable and how to fix it?
declare var myGlobalVar: Function;
const myFunction = async() {
//doing stuff
//calling myGlobalVar which give me following error
}
error i get while running serviceWorker:
:Uncaught (in promise) ReferenceError: myGlobalVar is not defined
Upvotes: 1
Views: 1381
Reputation: 9458
This isn't a TypeScript issue (... well, not directly), this is a JavaScript issue.
declare
tells the TS compiler to bugger off and trust you that that variable will be available at runtime. It's a contract between you and your code. It does not provide anything to the runtime. declare
d variables are called "ambient" for this reason - they go away during compilation.
See this for more information on Ambient Declarations.
You're missing, on the JavaScript side, the declaration of myFunction
. For example,
<script type="text/javascript">
function myGlobalVar() {
// whatever
}
</script>
<script src="../bundle.js"></script>
where bundle.js
is the output of tsc
.
Upvotes: 1