37
12

More than 3 years have passed since last update.

オブジェクトのkeyをtypeで指定する(Mapped types)

Last updated at Posted at 2020-02-04

オブジェクトの key を型で指定したい

type Side = 'send' | 'receive'

function sideCharObj(): { [key: Side]: string } {
  return {
    send: '',
    receive: ''
  }
},

{ [key: string]: string } のように書けそうだが、
これだと下記のエラーが出る
An index signature parameter type cannot be a union type. Consider using a mapped object type instead.

Mapped types で key の型を指定

type Side = 'send' | 'receive'

function sideCharObj(): { [key in Side]: string } {
  return {
    send: '',
    receive: ''
  }
}

:x: { [key: Side]: string }
:o: { [key in Side]: string }

参考

こちらに、Mapped types についての詳しい記事がありました
https://qiita.com/Quramy/items/e27a7756170d06bef22a#mapped-types

37
12
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
37
12