Skip to content

Instantly share code, notes, and snippets.

@orion55
Last active August 22, 2023 05:38
Show Gist options
  • Save orion55/e87686370755edffe817b60daf273f40 to your computer and use it in GitHub Desktop.
Save orion55/e87686370755edffe817b60daf273f40 to your computer and use it in GitHub Desktop.
filterUsers
interface User {
type: 'user';
name: string;
age: number;
occupation: string;
}
interface Admin {
type: 'admin';
name: string;
age: number;
role: string;
}
export type Person = User | Admin;
export function filterUsers(persons: Person[], criteria: Partial<Omit<User, 'type'>>): User[] {
return persons.filter(isUser).filter((user) => {
const criteriaKeys = Object.keys(criteria) as (keyof Omit<User, 'type'>)[];
return criteriaKeys.every((fieldName) => {
return user[fieldName] === criteria[fieldName];
});
});
}
console.log('Users of age 23:');
filterUsers(
persons,
{
age: 23
}
).forEach(logPerson);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment