Typescript: Working with Models

In this example below you will see how to do a Typescript: Working with Models with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by alaneicker, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright alaneicker ©
  • HTML
  • CSS
  • JavaScript
    

/*Downloaded from https://www.codeseek.co/alaneicker/typescript-working-with-models-Qmoood */
    


/*Downloaded from https://www.codeseek.co/alaneicker/typescript-working-with-models-Qmoood */
    // User interface
interface IUser {
  id?: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
}

// User model
class User {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  
  constructor(newUser: IUser) {
    this.id = newUser.id ? newUser.id : User.createId();
    this.firstName = newUser.firstName;
    this.lastName = newUser.lastName;
    this.email = newUser.email;
    this.phone = newUser.email;
  }
  
  static createId() {
    return `user-${Math.round(Math.random() * 1000000)}`;
  }
}

// User service
class UserService { 
  users: IUser[];
  
  constructor() {
    this.users = [];
  }
  
  get getUsers(): IUser[] {
    return this.users;
  }
  
  getUserById(id: string): IUser {
    return this.users.find(user => user.id === id);
  }
  
  addUser(newUser: IUser): void {
    this.users.push(new User(newUser));
  }
}

// Create an instance of Users and add some users.
let userService = new UserService();

userService.addUser({
  id: 'custom-user-id',
  firstName: 'John',
  lastName: 'Doe',
  email: 'jdoe@gmail.com',
  phone: '312-333-4567',
});

userService.addUser({
  firstName: 'Fred',
  lastName: 'Flintstone',
  email: 'fred_flintstone@yahoo.com',
  phone: '773-342-3458',
});

// Gets All users 
console.log(userService.getUsers);

// Gets user by ID
console.log(userService.getUserById('custom-user-id'));

Comments