LoginSignup
0
0

More than 1 year has passed since last update.

Object.keys()の型がstring[]になる問題の対策(キャスト使わない版)

Last updated at Posted at 2021-05-28

キャストは使わずにやりたい。ほどほどにtype safeにしたい

TL;DR;

Object.keys()使わずにfor inを使う

const obj = {
  FOO: "foo",
  BAR: "bar",
  BAZ: "baz",
};

let key: keyof typeof obj;
for (key in obj) {
  const value = obj[key];
  // 
}

(参考)キャスト使ってもOKなら....


const keys = Object.keys(obj) as (keyof typeof obj)[];
keys.forEach((key) => {
  const value = obj[key];
  //   
});
0
0
1

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