LoginSignup
163
108

More than 1 year has passed since last update.

TypeScriptで条件分岐時の可読性の高い変数設定

Last updated at Posted at 2022-08-02

本記事を対象とする人

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

結論 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を積極的に活用していこうかと考えています。

163
108
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
163
108