好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

TypeScript中条件分支时具有高可读性的变量设置

本記事を対象とする人

TS,JSで極力letではなくconstを使うべきと思っている人

結論 ts-patternが便利

https://github.com/gvergnaud/ts-pattern

解説

何かのオブジェクトを参照して場合分けして、変数を定義したい場合があると思います

    let   platform   =   ''  ; 
   if   (  game  .  name   ===   '  ff3  '  )   { 
     platform   =   '  fc  '  ; 
   }   else   if   (  game  .  name   ===   '  ff4  '  )   { 
     platform   =   '  sfc  '  ; 
   } 
 

このケースでletは使いたくないため、こうする

    const   platform   =   (()   =>   { 
     if   (  game  .  name   ===   '  ff3  '  )   { 
       return   '  fc  '  ; 
     }   else   if   (  game  .  name   ===   '  ff4  '  )   { 
       return   '  sfc  '  ; 
     } 
     return   ''  ; 
   })(); 
 //---or 
   const   platform   =   (()   =>   { 
     switch   (  game  .  name  )   { 
       case   '  ff3  '  : 
         return   '  fc  '  ; 
       case   '  ff4  '  : 
         return   '  sfc  '  ; 
     } 
     return   ''  ; 
   })(); 
 

このようなケースの場合、nameの一つの変数だけ参照すればよいためまあよいか、となるが
2つ変数の参照が必要になった場合一気に可読性が悪くなる

    const   gameName   =   (()   =>   { 
     if   (  game  .  genre   ===   '  rpg  '  )   { 
       if   (  game  .  company   ===   '  enix  '  )   { 
         return   '  dq1  '  ; 
       }   else   if   (  game  .  company   ===   '  nintendo  '  )   { 
         return   '  pokemon  '  ; 
       } 
       return   '  ff1  '  ; 
     }   else   if   (  game  .  genre   ===   '  simulation  '  )   { 
       if   (  game  .  company   ===   '  maxis  '  )   { 
         return   '  simcity  '  ; 
       } 
       return   ''  ; 
     } 
     return   ''  ; 
   })(); 
 

ts-patternを使う

ぱっと見でwithで何を判定して何を返すかわかりやすくなり
かつ、constにできました。

    const   gameName   =   match  (  game  ) 
     .  with  ({   genre  :   '  rpg  '  ,   company  :   '  enix  '   },   ()   =>   '  dq1  '  ) 
     .  with  ({   genre  :   '  rpg  '  ,   company  :   '  nintendo  '   },   ()   =>   '  pokemon  '  ) 
     .  with  ({   genre  :   '  rpg  '   },   ()   =>   '  ff1  '  ) 
     .  with  ({   genre  :   '  simulation  '  ,   company  :   '  maxis  '   },   ()   =>   '  simcity  '  ) 
     .  otherwise  (()   =>   ''  ); 
 

ということで、分岐して変数を設定する場合にはts-patternを積極的に活用していこうかと考えています。


原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308622221.html

查看更多关于TypeScript中条件分支时具有高可读性的变量设置的详细内容...

  阅读:47次