0
0

More than 1 year has passed since last update.

バリデーションの条件をオブジェクトにまとめてfor-ofで回す

Last updated at Posted at 2023-02-12

課題

バリデーションの条件毎にif文を書いて分岐すると、同じ処理が重複するのでスマートではない。

解決策

条件とアラートメッセージをオブジェクトにまとめてfor-ofで回す

コード内容

validate.ts
const validateInputData = (file: File): boolean => {
  type ErrorType = {
    term: boolean;
    message: string;
  };
  const err: { [key: string]: ErrorType } = {
    notJson: {
      term: file.name.slice(-4).toLowerCase() !== 'json',
      message: 'Not json file.',
    },
    notAllow: {
      term: Object.keys(JSON.parse(JSON.stringify(file))).length === 0,
      message: 'This file is not allowed.',
    },
  };
  const errText = ' Please select another.';
  for (const key in err) {
    if (err[key].term) {
      alertWindow(err[key].message + errText);
      return false;
    }
  }
  return true;
};

POINT

for-ofで条件とアラートのメッセージを1つの記述で回す

errオブジェクトから取得したキーを使います。

validate.ts
  for (const key in err) {
    if (err[key].term) {
      alertWindow(err[key].message + errText);
      return false;
    }
  }

Mapped Typeを活用して型安全にする

keyの型をstringに指定することで、for-ofの型エラーを防ぎます。
(これをしておかないとerr[key]でエラーになる)

validate.ts
  type ErrorType = {
    term: boolean;
    message: string;
  };
  const err: { [key: string]: ErrorType } = {
    notJson: {
      term: file.name.slice(-4).toLowerCase() !== 'json',
      message: 'Not json file.',
    },
  };
0
0
0

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
0
0