javascripttypescriptvue.jsflickityvue-flickity

TypeScript + Vue 3 - ReferenceError: variable is not defined


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>

Solution

  • 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())