📌

Reactで動的なものをつくる

に公開2


コード


    const apple = {
      name: 'apple',
      color: 'red',
      season: 'winter'
    }

    const food = {
      fruits: apple,
      vegetables: {
        name: 'tomato',
        color: 'red',
        season: 'summer'
      } // もちろんこれもいける
    }

    const type = 'fruits' // ここに動的に値が入るようにすればOK
    console.log(food[type])
    // >> {name: 'apple', color: 'red', season: 'winter'}

    console.log(food['vegetables'].name) // これもいける
    // >> tomato
   

参考資料

Discussion

jonchonjonchon

エラー①

型 'string' の式を使用して型 '{ stone: string; note: string; image: string; }' にインデックスを付けることはできないため、要素は暗黙的に 'any' 型になります。
  型 'string' のパラメーターを持つインデックス シグネチャが型 '{ stone: string; note: string; image: string; }' に見つかりませんでした。ts(7053)

(自分の)解決方法:keyの変数に対して、keyとして使われているもののみを型で定義する
参考資料:https://zenn.dev/katoaki/articles/37a8cff3a8a32a

jonchonjonchon

これはブラケット記法と言うらしい(?)