typescript - 类型“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;
},
];
}
解决方案
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,
}]
推荐阅读
- javascript - 使用 jquery 重置文本框不起作用
- pandas - 在熊猫中一起显示所有饼图
- python - 获取顶级文件夹的所有文件路径后,如何将它们全部写入新文件?
- laravel - 如何在视图中显示登录用户的订单数?
- flutter - 将文件写入和读取移动设备
- android - MutableStateOf 与 sharedPreferences 一起使用
- java - 从其他类向 JFrame 添加元素
- react-native - Amplify GraphQL 订阅不响应事件
- netlogo - 如何修复 netlogo 6.1.1 无名?已定义
- postgresql - 如果存在多个索引,Postgres 如何选择使用哪个索引?