【问题标题】:How to use Object.freeze in Vue with Typescript?如何在带有 Typescript 的 Vue 中使用 Object.freeze?
【发布时间】:2022-01-06 23:21:49
【问题描述】:

有一个例子:

<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 会报告:Type 'readonly { t: number; l:数字; }[]' 是 'readonly' 并且不能分配给可变类型 '{ t: string; l:字符串; }[]'。

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    将您的数据属性 flags 设为只读数组,以便为​​其分配响应:

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

    【讨论】:

    • flags: readonly Record&lt;'t' | 'l', number&gt;[] 会更好
    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 2020-12-01
    • 2019-02-02
    • 2019-08-27
    • 2021-03-24
    • 2023-03-20
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多