52
28

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 5 years have passed since last update.

Object.keysの型がstring[]になってしまう問題の対策

Last updated at Posted at 2019-07-26

問題

以下のようなコードを書くと、data[key]でエラーになる。

const data = {
    apple: 'ringo',
    organge: 'mikan',
    pear: 'nashi'
}

const rows = Object.keys(data).map((key) => {
    return { key, value: data[key] }
})
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ apple: string; organge: string; pear: string; }'.
  No index signature with a parameter of type 'string' was found on type '{ apple: string; organge: string; pear: string; }'.

理由

Object.keysの返り値がstring[]になるけど、data[key]したときにdataのindexが列挙型なので、stringと不一致するため。

対策

keyofを使うといい。

type Data = {
    apple: string,
    orange: string,
    pear: string
}
const data: Data = {
    apple: 'ringo',
    orange: 'mikan',
    pear: 'nashi'
}

const rows = (Object.keys(data) as (keyof Data)[]).map((key) => {
    return { key, value: data[key] }
})

keyofで指定した型のキーを列挙した型を返してくれる。
Object.keys(data) as (keyof Data)することで、dataのキーの列挙型が帰ってくるので、それを配列にしてから.mapに渡せばkeyが列挙型になりエラーにならなくなるという

52
28
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
52
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?