Home > Back-end >  How to use Object.freeze in Vue with Typescript?
How to use Object.freeze in Vue with Typescript?

Time:11-30

There is an example:

<template>
  <h1>hello</h1>
</template>

<script lang="ts">
import Vue from 'vue'

type DataOptions = {
  name: string
  age: number
  flags: { t: number; l: number }[]
}

export default Vue.extend({
  name: 'HelloWorld',

  data(): DataOptions {
    return {
      name: 'zs',
      age: 18,
      flags: []
    }
  },

  methods: {
    refresh() {
      const response = [
        { t: 1, l: 1 },
        { t: 2, l: 2 }
      ]

      this.flags = Object.freeze(response)
    }
  }
})
</script>

Typescript will report: The type 'readonly { t: number; l: number; }[]' is 'readonly' and cannot be assigned to the mutable type '{ t: string; l: string; }[]'.

CodePudding user response:

Make your data property flags as a readonly array in order to assign response to it :

type DataOptions = {
  name: string
  age: number
  flags: ReadonlyArray<Record<'t'|'l', number>>
}
  • Related