0

I declare a variable to have type any at the beginning of my <script> and I later reference it in one of my methods in this same <script>. My IDE doesn't complain at all but surprisingly I see a runtime error in my console: ReferenceError: flik is not defined.

Maybe this has something to do with the a race condition around variable instantiation within Vue's lifecycle? It's confusing because I don't have this problem using a similar pattern elsewhere. What's wrong with my code below?

<script lang="ts">
import Flickity from "./widgets/Flickity.vue";

declare var flik: any

export default defineComponent({
  components: {
    Flickity
  },
  methods: {
    addElement() {
      flik = this.$refs.flickity    //ERROR HERE: flik is undefined
      flik.append(this.makeFlickityCell())
    },
    makeCell() {
      const cell = document.createElement('div');
      cell.className = 'carousel-cell'
      cell.textContent = "Hi"
      return cell
    }
  },
  mounted() {
    this.addElement()
  }
});
</script>
Cody
  • 1,801
  • 3
  • 28
  • 53

1 Answers1

2

I don't see a need for the declare here, which actually tells the TypeScript compiler that flik is already declared elsewhere (e.g., it's a global).

Just use type assertion as any:

(this.$refs.flickity as any).append(this.makeFlickityCell())
tony19
  • 125,647
  • 18
  • 229
  • 307
  • Hm, trying this approach "works", but just causes a different runtime error on this line instead: `Cannot read property 'append' of undefined` – Cody Jun 30 '21 at 15:52
  • Glad it worked for you. The new error implies that the template ref doesn't exist, and is beyond the scope of this question. Note the error is *not* caused by TypeScript. – tony19 Jun 30 '21 at 19:19