Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

TypeScript学習日記 その0009 readonlyな文字列の配列をキーとしてオブジェクトを作成する関数

参考にさせていただいたページ

makeObj.tsに関数を定義する

以下のような関数を定義します。

type MyKeys<T extends string> = readonly T[]

export default function makeObj<K extends string, T>(
  myKeys: MyKeys<K>,
  defaultValue: T
): Record<K, T> {
  const myObj = {} as Record<K, T>;
  for (const key of myKeys) {
    myObj[key] = defaultValue
  }

  return myObj
}

任意のファイルにimportして実行する

以下のようにimportして関数を実行すると任意のプリミティブ型の初期値を持ったオブジェクトが作成できます。

import makeObj from '~/utils/makeObj'

const myKeys = [
  'key1',
  'key2',
  'key3',
] as const

const myStrObj = makeObj(myKeys, '')
const myBooleanObj = makeObj(myKeys, false)
const myStrArrObj = makeObj(myKeys, [] as string[])
const my0bj = makeObj(myKeys, makeObj(['hoge', 'foo'] as const, ''))