Vue3:使用 TypeScript 时无法从另一个计算道具访问计算道具

Vue3: cannot access computed prop from another computed prop when using TypeScript

我有一个带有 TypeScript 的 Vue3 项目,我发现我无法从一个计算 属性 访问另一个计算 [=27] 返回的 JS 对象的属性(使用点符号或命名索引) =].

所以给定下面的代码,我的 TS 编译器将在尝试读取 this.user 对象上的 friends 时出现编译错误。这是有道理的,因为 this.user 是一个函数,但在 Vue 世界中它被视为 属性。如果删除 lang="ts" 部分,代码将正常工作。

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "HelloWorld",
  props: {
    msg: String,
  },
  computed: {
    user: function(): { friends: [] } {
      return { friends: [] };
    },
    formattedFriends: function() {
      return this.user.friends.map((f: any) => f);
    },
  },
});
</script>

这里是错误:

Failed to compile.

src/components/HelloWorld.vue:92:24
TS2339: Property 'friends' does not exist on type '() => { friends: never[]; }'.
    90 |     },
    91 |     formattedFriends: function() {
  > 92 |       return this.user.friends.map((f: any) => f);
       |                        ^^^^^^^
    93 |     },
    94 |   },
    95 | });

我使用 Vue cli (vue create) 创建了这个示例代码。

我不确定这是否是 TypeScript 或 Vue 的问题?有任何想法吗?我不想删除这段代码的 TypeScript 标签,但这可能是最好的选择。

可能不是最好的解决方案,但我想你可以通过指定 this 参数来安抚编译器..

formattedFriends: function(this: any) { // or a stricter type if you wish
  return this.user.friends.map((f: any) => f);
},

一种方法是在访问之前转换类型:

computed: {
    user: function(): { friends: [] } {
        return { friends: [] };
    },
    formattedFriends: function() {
        const typedUser = (this.user as { friends: [] })
        
        return typedUser.friends.map((f: any) => f);
    },
},

想知道是否有更好的方法。

不确定您的用户计算应该做什么,因为它没有反应源?

然而,在 Vue3 中,使用反应性 API 并执行类似

的操作会更好
export default defineComponent({
  name: "HelloWorld",
  props: {
    msg: String,
  },
  setup() {
    const user = reactive({friends:[]})
    const formattedFriends = computed(() => user.friends.map((f : any) => f))
    return {
      user,
      formattedFriends
    }
  },
});