SHARE
TWEET

Modeling from JSON in Typescript.

fueanta Jun 5th, 2020 (edited) 779 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Type {
  2.     _kind: string;
  3.     _breed: string;
  4.  
  5.     constructor(typeObj: any) {
  6.         this._kind = typeObj.kind;
  7.         this._breed = typeObj.breed;
  8.     }
  9. }
  10.  
  11. class Pet {
  12.     private _name: string;
  13.     private _age: number;
  14.     private _type: Type;
  15.     private _mealCount: number;
  16.  
  17.     constructor(petObj: any) {
  18.         this._name = petObj.name;
  19.         this._age = petObj.age;
  20.         this._type = new Type(petObj.extra.type);
  21.         this._mealCount = petObj.extra.meals.length;
  22.     }
  23.  
  24.     getDescription = (): string =>
  25.         `My ${this._name} is a ${this._type._breed} ${this._type._kind}.\n` +
  26.         `She is ${this._age} year(s) old.\n` +
  27.         `She takes ${this._mealCount} meal(s) everyday.`;
  28. }
  29.  
  30.  
  31.  
  32.  
  33. const pet: Pet = new Pet(JSON.parse(
  34.     '{"name":"Fido","age":5,"extra":{"id":1234,"type":{"kind":"Cat","breed":"Parsian"},"meals":["Cat Food","Tuna Can","Boiled Chicken"]}}'
  35. ));
  36.  
  37. console.log(pet.getDescription());
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top