gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:10:29 24 4
gpt4 key购买 nike

我有一个带有 TypeScript 的 Vue3 项目,我发现我无法从另一个计算属性中的一个计算属性访问返回的 JS 对象的属性(使用点表示法或命名索引)。
因此,鉴于下面的代码,我的 TS 编译器在尝试读取 friends 时会出现编译错误。在 this.user目的。这是有道理的 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);
},

关于javascript - Vue3 : cannot access computed prop from another computed prop when using TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66055201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com