Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
16
Help us understand the problem. What is going on with this article?
@mizuki_r

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

More than 1 year has passed since last update.

問題

以下のようなコードを書くと、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が列挙型になりエラーにならなくなるという

16
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
mizuki_r
bengo4
「専門家をもっと身近に」を理念として、人々と専門家をつなぐポータルサイト「弁護士ドットコム」「弁護士ドットコムニュース」「税理士ドットコム」を提供。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
16
Help us understand the problem. What is going on with this article?