【问题标题】:Property does not exist on type in computed function计算函数中的类型不存在属性
【发布时间】:2020-07-24 13:29:22
【问题描述】:

我是 TypeScript 的新手。下面的代码在 JavaScript 上运行没有问题,但是这里没有编译。

export default {
  data: function() {
    return {
      data: [
        'Angular',
        'Angular 2',
        'Aurelia',
        'Backbone',
        'Ember',
        'jQuery',
        'Meteor',
        'Node.js',
        'Polymer',
        'React',
        'RxJS',
        'Vue.js'
      ],
      name: "",
      selected: null,
      hasVariationRadio: ""
    };
  },
  computed: {
    filteredDataArray(): [] {
      return this.data.filter((option: string) => { // This is where the error appears
        return option
          .toString()
          .toLowerCase()
          .indexOf(this.name.toLowerCase()) >= 0 // Also here.
      })
    }
  }
};

我收到以下错误: Property 'name' does not exist on type '{ filteredDataArray(): []; }'.

here 所述,stricttsconfig.json 文件中的 compilerOptions 内设置为 true

【问题讨论】:

  • 我无法重现您在我的设置中提到的错误(选择了带有 TypeScript 选项的 Vue CLI 项目)。我得到一个不同的错误:Type 'string[]' is not assignable to type '[]',但是将filteredDataArray() 的返回类型设置为string[] 可以解决它。

标签: typescript vue.js


【解决方案1】:

当我在控制台中运行这段代码时,它似乎并不正确。

当您在 computed.filteredDataArray 中引用 this 时,thiscomputed 对象,而不是全部。

filteredDataArray 移动更高一级使其工作:

export default {
    data: function () {
        return {
            data: [
                'Angular',
                'Angular 2',
                'Aurelia',
                'Backbone',
                'Ember',
                'jQuery',
                'Meteor',
                'Node.js',
                'Polymer',
                'React',
                'RxJS',
                'Vue.js'
            ],
            name: "",
            selected: null,
            hasVariationRadio: ""
        };
    },
    filteredDataArray() {
        return this.data().data.filter((option: string) => {
            return option
                .toString()
                .toLowerCase()
                .indexOf(this.data().name.toLowerCase()) >= 0
        })
    }
};

【讨论】:

  • 在删除 TypeScript 特定的返回类型后,当 lang 设置为 JavaScript 没有问题时,问题上的代码有效。如果有帮助,它位于 Vue 组件中。
  • @Karol 有问题的代码定义了一个Vue component,其中filteredDataArray 是一个computed prop
猜你喜欢
  • 1970-01-01
  • 2020-08-02
  • 2022-01-03
  • 2018-09-21
  • 2021-11-30
  • 2014-11-04
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多