2

If i have an Stencil.js component that i load in to my Vue project like this:

index.html:

  <script type="module"
    src="https://xxxxxx.s3-eu-west-1.amazonaws.com/topbar.esm.js">
  </script>

  <script>
    window.addEventListener('topbarLoaded', function (data) {
      window.topbar = data.detail;
      console.log('topbar was loaded and here it is:', window.topbar);
    });
  </script>

I then want to reach the topbar information in my vue components. Something like

VueComponent.vue

<script lang="ts">
   import { Component, Prop, Vue } from "vue-property-decorator";

   @Component({
     name: 'testcomp'
   })
   export default class PodList extends Vue {
      data() {
         return {
            topbar: window.topbar // Error: Property 'topbar' does not exist on type 'Window & typeof globalThis'
         }
      }
   }
</script>

So here I want all stuff i have from my topbar to be accessible in my Vue component. As it is now, if I open Chrome devtools i can write topbar.user and get all information of user, but I also want this information to be reachable in all vue components.

Johan Byrén
  • 890
  • 2
  • 13
  • 28
  • 1
    Is there any reason you can't just listen to that even from within your component? – Ohgodwhy Feb 06 '20 at 17:25
  • True, I moved it to my main.ts. I want to set an axios header with a token that the topbar is fetching. So now i moved to eventListener to main.ts, and that sets header like this: `axios.defaults.headers.common['Authorization'] = await topbar.access_token();` Here is the code in main.ts: `window.addEventListener('topbarLoaded', async function (data) { const topbar = (data as any); var topbarDetails = topbar.detail; axios.defaults.headers.common['Authorization'] = await topbarDetails.access_token(); });` – Johan Byrén Feb 07 '20 at 14:12

1 Answers1

2

The problem is that TypeScript doesn't know that property. You can solve that in several ways:

  1. Add // @ts-ignore on the previous line. This suppresses errors on the next line.
  2. Cast to any: (window as any).topbar
  3. Define the property in the window interface:
declare global {
    interface Window { topbar: any; }
}
Thomas
  • 8,426
  • 1
  • 25
  • 49
  • 2
    Solution 3 is what I would have recommended as well because it gives you the option to add the actual type declaration for `topbar`, and it makes it clear that `topbar` is something that has been added to the global scope. – Simon Hänisch Feb 08 '20 at 00:34