Wednesday, March 7, 2018

Avoid newing up classes in a mapping operation in TypeScript in the name of making code less verbose.

This...

saveStuff(): void {
   this.felines = this.cats.map((cat: Cat) => {
      let feline = new Feline();
      feline.Id = cat.Collar.Tag.SerialNumber;
      feline.Name = cat.Name;
      feline.NumberOfLives = cat.LivesRemaining;
      return feline;
   });
}

 
 

...could be cleaned up like so:

saveStuff(): void {
   this.felines = this.cats.map((cat: Cat) => ({
      Id: cat.Collar.Tag.SerialNumber,
      Name: cat.Name,
      NumberOfLives: cat.LivesRemaining
   }));
}

 
 

Depending on you, you may want a type assertion tossed in too.

saveStuff(): void {
   this.felines = this.cats.map((cat: Cat) => (<Feline>{
      Id: cat.Collar.Tag.SerialNumber,
      Name: cat.Name,
      NumberOfLives: cat.LivesRemaining
   }));
}

 
 

This is legitimate too which surprised me.

saveStuff(): void {
   this.felines = this.cats.map((cat: Cat) => <Feline>({
      Id: cat.Collar.Tag.SerialNumber,
      Name: cat.Name,
      NumberOfLives: cat.LivesRemaining
   }));
}

 
 

Even this will compile and assert (twice over) but I don't recommend it...

saveStuff(): void {
   this.felines = this.cats.map((cat: Cat) => <Feline>(<Feline>{
      Id: cat.Collar.Tag.SerialNumber,
      Name: cat.Name,
      NumberOfLives: cat.LivesRemaining
   }));
}

No comments:

Post a Comment