首页 > 解决方案 > 类型“any[]”中缺少属性“0”,但类型“[{ post_id: string; 标题:字符串;}]'

问题描述

我看过这篇文章,但我仍然不明白问题是什么..为什么我不能将此数组传递给更新调用?

    // 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;
    },
  ];
}

标签: typescriptnestjs

解决方案


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,
}]

推荐阅读