Advertisement
Gygaweb

Object oriented proggramming example

Feb 18th, 2023 (edited)
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 0.59 KB | Software | 0 0
  1. class User {
  2.   id: number;
  3.   name: string;
  4.   email: string;
  5.  
  6.   constructor(id: number, name: string, email: string) {
  7.     this.id = id;
  8.     this.name = name;
  9.     this.email = email;
  10.   }
  11.  
  12.   static getById(id: number, users: User[]): User | undefined {
  13.     return users.find(user => user.id === id);
  14.   }
  15. }
  16.  
  17. const users = [
  18.   new User(1, 'Alice', 'alice@example.com'),
  19.   new User(2, 'Bob', 'bob@example.com'),
  20.   new User(3, 'Charlie', 'charlie@example.com'),
  21. ];
  22.  
  23. const user = User.getById(2, users);
  24. if (user) {
  25.   console.log(user.name);
  26. } else {
  27.   console.log('User not found');
  28. }
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement