【问题标题】:Property '0' is missing in type 'any[]' but required in type '[{ post_id: string; title: string; }]'类型“any[]”中缺少属性“0”,但类型“[{ post_id: string;标题:字符串; }]'
【发布时间】:2020-05-18 19:14:25
【问题描述】:

我查看了这个post,但我仍然不明白问题出在哪里。为什么我不能将此数组传递给更新调用?

    // create object with new post props
    const newPost = await this.postRepository.create(data);
    await this.postRepository.save(newPost);

    // push postid into posts array
    const posts = [];
    posts.push({
      post_id: newPost.post_id,
      title: newPost.title,
    });

    const updatedUser = {
      posts,
    };

    // update user to contain the posts array
    await this.userService.edit(data.user_id, updatedUser); // error on updatedUser

export interface UserDTO {
  user_id: string;
  name: string;
  posts: [
    {
      post_id: string;
      title: string;
    },
  ];
}

【问题讨论】:

  • 明确输入帖子变量有帮助吗? const posts: UserDTO['posts'] = [];。另外,我认为这不是您界面中的有效语法。试试posts: Array<{ post_id... }>;
  • 语法[T] 是有效的,但它是在谈论tuple,在这种情况下,是一个由T 类型的元素组成的数组。如果您想要一个包含零个或多个 T 类型元素的数组,则应使用 T[] 或等效的 Array<T>

标签: typescript nestjs


【解决方案1】:
posts: [
    {
      post_id: string;
      title: string;
    },
  ];

这使得posts 成为tuple,而不是(只是)一个数组。意思是posts 将只有一个元素,并且该元素的类型为{ post_id: string, title: string }

当你创建这个数组时:

const posts = [];

...它只是一个简单的any 数组。它可能有 1 个元素,或更多或更少。因此它与元组不匹配,因为无法强制它具有正确的内容。

很可能,将其设置为元组是错误的,您应该将类​​型定义更改为:

posts: {
  post_id: string;
  title: string;
}[]

另一方面,如果它应该是一个元组,那么你需要将变量也设为该类型,如下所示:

const posts: [{ post_id: string, title: string }] = [{
  post_id: newPost.post_id,
  title: newPost.title,
}]

【讨论】:

    【解决方案2】:

    这不是一个数组!它是一个元组,只包含一个元素。

    posts: [
        {
          post_id: string;
          title: string;
        },
    ]
    

    你想要的是一个数组:

    posts: {
      post_id: string;
      title: string;
    }[]
    

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 2019-06-25
      • 2021-10-02
      • 1970-01-01
      • 2019-04-28
      • 2018-03-03
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多