【发布时间】:2021-05-09 07:38:53
【问题描述】:
我有一个带有 TypeScript 的 Vue3 项目,我发现我无法从另一个计算属性中的一个计算属性访问返回的 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 标记,但可能是最好的选择。
【问题讨论】:
标签: javascript typescript vue.js vuejs3