自定义对象返回错误:类型"void"上不存在属性'forEach'.ts(2339)



我有一个变量,要么是类User,要么是void类,唯一的问题是当我运行这段代码时,它给了我一个错误:Property 'forEach' does not exist on type 'void'.ts(2339)。我试图用一百种不同的方式解决这个问题,但没有任何效果。

let friends: [User] | void = await this.getFriendsPosts(host);
friends.forEach(element => {
});

更新:

以下是函数this.getFriendsPosts(host)和其他后续函数的代码:

async getFriendsPosts(host: User){
let userFriendsID = host.friends
let userFriends = []
let retrievedPosts: [Post[]?] = []
userFriendsID.map(async uid =>{
let val = new User(await this.checkFriend(uid))
userFriends.push(val)
console.log(userFriends)
})
}

//*convert to users with promises
async checkFriend(uid){
let metaData;
let postInterface= [];
let friendInterface : unknown;
//*getting the post history
let promise1 = new Promise((res, rej) => {
metaData = 
this.firestore.collection('Users').doc(uid.toString())
let postData = metaData.collection('Posts')
postData.valueChanges().subscribe(vals =>{
vals.forEach(input => {
postInterface.push({
title: input.title,
id: input.id,
user: input.user,
timebomb: input.timebomb,
type: input.type,
timestamp: input.timestamp
} as complexPostInterface)      
})
res(vals)
})
})
//*getting the user stats
let promise2 = new Promise((res, rej) => {
metaData.valueChanges().subscribe(vals =>{
friendInterface = {
name: vals.name,
uid: vals.uid,
nickname: vals.nickname,
currentPosts: postInterface,
status: new Post(postInterface[0] as any),
timestamp: vals.timestamp,
} as complexUserObj
res(friendInterface as complexUserObj)
})
})
await Promise.all([promise1,promise2])
console.log(friendInterface)
return (friendInterface)
}

你的getFriendsPosts方法应该返回undefined而不是void。Void 应该用于返回值将被忽略的函数中。

属性 'forEach' 在未定义时也不存在,所以你需要先检查朋友是否存在:

let friends: [User] | undefined = await this.getFriendsPosts(host);
if (friends) {
friends.forEach(element => {
});
}

或者,或者使该方法返回一个空的用户数组,而您无需检查它。

最新更新