[英]Custom Object Returning Error: Property 'forEach' does not exist on type 'void'.ts(2339)
I have a variable that will either be of a class User
or void
, the only problem is that when I run this code it gives me an error of: Property 'forEach' does not exist on type 'void'.ts(2339)
.我有一个变量,它要么是 class User
要么是void
,唯一的问题是当我运行这段代码时它给我一个错误: Property 'forEach' does not exist on type 'void'.ts(2339)
。 I have tried to work around this a hundred different ways, but nothing works.我尝试过一百种不同的方法来解决这个问题,但没有任何效果。
let friends: [User] | void = await this.getFriendsPosts(host);
friends.forEach(element => {
});
Update:更新:
Here is my code for the function this.getFriendsPosts(host)
and other subsequent functions:这是我的 function this.getFriendsPosts 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)
}
Your getFriendsPosts method should return undefined instead of void.您的 getFriendsPosts 方法应该返回 undefined 而不是 void。 Void should be used in functions whose return value will be ignored. Void 应该用在返回值将被忽略的函数中。
Property 'forEach' does not exist on undefined either, so you'll need to check first that friends exist:属性 'forEach' 也不存在于 undefined 上,因此您需要首先检查 friends 是否存在:
let friends: [User] | undefined = await this.getFriendsPosts(host);
if (friends) {
friends.forEach(element => {
});
}
Or alternatively make the method return an empty array of Users and you don't need to check for it.或者让该方法返回一个空的 Users 数组,您不需要检查它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.