1
3

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.

連想配列のキーをtypeで定義したら、Object.keys()の型はasで明示(TypeScript)

Posted at

TypeScriptで、以下のような感じに連想配列のキーをtypeで定義すると、使用されるキーが限定されます。考慮する生活費(LivingCost)の費目が固定されていい感じです。

export type LivingCostTypes =
  | 'house'
  | 'food'
  | 'energy'

export type LivingCost = {
 [key in LivingCostTypes]: number
}

さて、この生活費の合計を求めたくなったとき、Object.keysでループしたくなります。しかし、Object.keys(livingCost)と書くだけでは費目としてどんなstringが来るか不明なのでエラーになります。

export function getLivingCostTotal(livingCost: LivingCost): number {
  let cost = 0
  Object.keys(livingCost).forEach(v => {
    cost += livingCost[v]
  }, 0)
  return cost
}
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'LivingCost'.
  No index signature with a parameter of type 'string' was found on type 'LivingCost'.ts(7053)

このときは、Object.keysの中身をasで明示してあげるとエラーが解消されます。

export function getLivingCostTotal(livingCost: LivingCost): number {
  let cost = 0
  const keys = Object.keys(livingCost) as LivingCostTypes[]
  keys.forEach(v => {
    cost += livingCost[v]
  }, 0)
  return cost
}
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?