【问题标题】:Vue3 reactive nested object and optional typingsVue3 反应式嵌套对象和可选类型
【发布时间】:2021-06-16 17:40:22
【问题描述】:

我似乎偶然发现了一些挑战......也许是 Vue3 中的一个错误,带有 Typescript 和组合 API,或者我可能忽略了一些东西。

如果我有一个类型为可选的对象,我在我的 IDE (Webstorm) 中没有得到任何智能感知:

我已经设置了这个小例子: 有了这个,你会期望在 .comment 之后打点时,你会得到“commentAuthor”作为对该对象的建议,但我不明白。但是,如果我在我的界面中告诉该评论不应该是可选的,我会得到正确的智能感知 - 如果您查看下面的附加图片,您会明白我的意思

<template>
  <h2>This is a Vue 3 component!</h2>
  {{ test.post.comment.commentAuthor }}
</template>

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

interface Comment {
  id: string;
  commentAuthor: string;
  topFriend?: {
    uid: string;
    name: string;
  };
}
interface Post {
  id: string;
  postContent: string;
  comment?: Comment;
}

export interface TestInterface {
  id: string;
  name: string;
  post: Post;
}

export default defineComponent({
  setup() {
    const test = reactive({
      id: "123",
      name: "John doe",
      post: {
        id: "333",
        postContent: "Lorem ipsum",
        comment: {
          id: "444",
          commentAuthor: "Jane Doe",
          topFriend: {
            uid: "555",
            name: "Donald Duck",
          },
        },
      },
    }) as TestInterface;

    return {
      test,
    };
  },
});
</script>

在我的界面中使用可选道具 With optional prop in my interface:

没有可选的道具 Without optional prop

为什么会这样?我认为它通常会有可选对象,所以我相信 Vue 应该能够处理这个?

【问题讨论】:

  • 您可以尝试使用可选链接运算符吗?如果对象是可选的,则无论如何都不应尝试访问它的属性而不先检查它。 - test.post.comment?.commentAuthor
  • 试过了,不工作...还尝试将其包装在 v-if="" - 这也没有成功:(
  • 智能感知是 IDE 为您做的事情。如果是 bug,那是 IDE(它用于“理解”Vue 文件的语言服务)的 bug,而不是 Vue 本身的 bug……
  • 别以为是编辑的问题——很确定……
  • 会不会和 ts.config 有关系?是否有任何选项可以告诉打字稿可选属性应该是“可用的”?如果不是默认情况下

标签: typescript vue.js webstorm vuejs3


【解决方案1】:

IDE有问题,请关注WEB-50101更新

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2020-04-21
    相关资源
    最近更新 更多