Skip to content

Instantly share code, notes, and snippets.

@LeeDDHH
Last active October 18, 2023 09:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeeDDHH/4bbb2e884d4649ed8193bd4e52f144fd to your computer and use it in GitHub Desktop.
Save LeeDDHH/4bbb2e884d4649ed8193bd4e52f144fd to your computer and use it in GitHub Desktop.
typescriptで他のプロジェクトでも流用できそうなコードを集めておく

ファイルの存在をチェックする

const isExistFile = (filePath: string) => {
  try {
    fs.statSync(filePath);
  } catch (e) {
    if (e.code === 'ENOENT') {
      console.log('file is not exists');
    }
    return false;
  }
  return true;
};

ファイルの存在チェックと存在しなかったら生成する

const makeFileIfNotExists = async (filePath: string, data: object) => {
  if (!isExistFile(filePath)) return await writeSync(filePath, data);
};

ディレクトリの存在チェックと存在しなかったら生成する

const makeDirIfNotExists = async (dirPath: string) => {
  if (!fs.existsSync(dirPath)) {
    try {
      await fs.promises.mkdir(dirPath, { recursive: true });
      return true;
    } catch (e) {
      console.log('mkdir failed: ' + e);
      return false;
    }
  }
  return true;
};

JSONデータとして書き出す

const writeSync = async (filePath: string, data: object) => {
  try {
    await fs.promises.writeFile(filePath, JSON.stringify(data, null, 2), {
      encoding: 'utf-8',
    });
  } catch (e) {
    console.log('write file failed: ' + e);
    return false;
  }
  return true;
};

JSONデータを読み込む

const readJsonFile = async (filePath: string) => {
  let content;
  try {
    content = await fs.promises.readFile(filePath, 'utf-8');
    return JSON.parse(content);
  } catch (e) {
    console.log('read file failed: ' + e);
    return null;
  }
};

指定されたディレクトリからJSON拡張子のファイルリストを取得する

const getJsonFileList = async (directoryPath: string) => {
  let list: string[];
  try {
    const logFileList = await fs.promises.readdir(directoryPath);
    list = logFileList
      .filter(async (file) => {
        const fileStat = await fs.promises.stat(path.join(directoryPath, file));
        return fileStat.isFile() && /.*\.json$/.test(file);
      });
  } catch (e) {
    console.log('directroy load falied: ' + e);
    return false;
  }
  return list;
};

オブジェクト内の特定の要素があるかどうかを確認する

const hasObjectProperty = (
  // 引数のタイプをObjectにするとeslintで怒られる
  // lintの説明とおり、 `any object` という意味だったので、推奨された `Record<string, unknown>` を使用
  obj: Record<string, unknown>,
  key: string
): boolean => {
  return (
    !!obj &&
    // Object.prototype.toString.call(obj)でobjを `[object 型名]` として文字列を表示するのでsliceで型名を取得する
    Object.prototype.toString.call(obj).slice(8, -1) === 'Object' &&
    Object.prototype.hasOwnProperty.call(obj, key)
  );
};

React、TypeScript構成で使えるpropsへ記述するEventCallbackの型の例

type Props = {
  onClick: (event: React.MouseEvent<HTMLInputElement>) => void
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void
  onkeypress: (event: React.KeyboardEvent<HTMLInputElement>) => void
  onBlur: (event: React.FocusEvent<HTMLInputElement>) => void
  onFocus: (event: React.FocusEvent<HTMLInputElement>) => void
  onSubmit: (event: React.FormEvent<HTMLFormElement>) => void
  onClickDiv: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
}

参考


Fetch APIで取得したjsonを任意の型で取得する

const apiCallWithFetch = async <T>(url: string): Promise<T> => {
  const response = await fetch(url);
  if (!response.ok) throw new Error(response.statusText);
  return response.json() as Promise<T>;
};

参考


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment