class User {
id: number;
name: string;
email: string;
constructor(id: number, name: string, email: string) {
this.id = id;
this.name = name;
this.email = email;
}
static getById(id: number, users: User[]): User | undefined {
return users.find(user => user.id === id);
}
}
const users = [
new User(1, 'Alice', '[email protected]'),
new User(2, 'Bob', '[email protected]'),
new User(3, 'Charlie', '[email protected]'),
];
const user = User.getById(2, users);
if (user) {
console.log(user.name);
} else {
console.log('User not found');
}