Reputation: 2285
How to filter an array of tow different types and get the targeted type, I used casing but I caused issues further in the code and I cannot use function predicated since I haven't isolated the value yet any idea how to this ?
the error I am getting on el.user is
Property 'user' does not exist on type 'UserType' | 'AdminType'
export type UserType = { user: string; data: string}
export type AdminType = { admin: string; data: string }
const usersAndAdminsArr =[{ admin: '2312'; data: 'blabla' }, { admin: '33123'; data: 'blabla' }, { user: '111'; data: '' }]
// get the array of filter users only (exclude admins)
const userType = usersAndAdminsArr.filter((el) => el.user === selected.user);
const isUser = (item: any): item is UserType => {
return item.user !== undefined;
};
Upvotes: 0
Views: 97
Reputation: 8962
You're not actually applying your type guard. You need to first filter out non UserType
objects, and then filter the users.
usersAndAdminsArr.filter(isUser).filter((userObj) => userObj.user === selected.user)
See playground and make sure you also take a look at Array.prototype.find()
Upvotes: 1