0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript】配列になったオブジェクトから、指定したプロパティのユニオン型を取り出す

Last updated at Posted at 2020-12-28

細かすぎて伝わらないタイトル

問題

例えば以下のような場合、onClickの引数にはvalueが取りうる'0' | '1' | '2'に縛りたい。

const numberDict = [
  {value: '0', label: 'ゼロ'},
  {value: '1', label: 'ワン'},
  {value: '2', label: 'ツー'},  
]

const onClick = (newValue: '0' | '1' | '2') => {  // 引数の型を動的に指定したい
  setLabel(newValue)
}

onClick(numberDict[0].value);

解決

type NumberDictValues = Pick<typeof numberDict[number], 'value'>['value']
const onClick = (
  newValue: NumberDictValues
) => {
  onClick(newValue)
}

詳細

考え方を順を追って説明します。

変数の型を導き出す。

まずはnumberDictの型を導出するため、typeofを使います。
numberDictas constでwideningを阻止します。

numberDict = {/* 略 */} as const
typeof numberDict

配列を展開する

配列の展開をします。
numberDict[number]という書き方をすると、インデックスアクセスで得られる値の型を出せます。

typeof numberDict[number]

参考

オブジェクトの値を抜き出す

最後にオブジェクトから値だけを抜き出します。
{}['key']という書き方でkeyでアクセスできる値をユニオン型で取得できます。

typeof numberDict[number]['value']
0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?