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.

リストからfindを使わずにキー指定でvalueを取得する方法&ts(7053)エラー対応簡易メモ

Last updated at Posted at 2020-11-30

やりたいこと

interface Hoge {
  id: number | string;
  value: string;
}

const hogeList: Hoge[] = [
 { id: 'A', value: 'a' },
 { id: 'B', value: 'b' },
 { id: 'C', value: 'c' },
];
const hogeList2: Hoge[] = [
 { id: 1, value: 'a' },
 { id: 2, value: 'b' },
 { id: 3, value: 'c' },
];

const byB = hogeList.find(hoge => hoge.id === 'B');
console.log(byB); // 'b'

const by3 = hogeList2.find(hoge => hoge.id === 3);
console.log(by3); // 'c'

hogeListリストから、
findを使わずにid指定でvalueを取得したい

方法

リストからidをキーにしたオブジェクトへ変換

const obj = toObjectFromList(hogeList);
console.log(obj['B']); // 'b'
console.log(obj); // Object{A: 'a', B: 'b', C: 'c'}

const obj2 = toObjectFromList(hogeList2);
console.log(obj2[3]); // 'c'
console.log(obj2); // Object{1: 'a', 2: 'b', 3: 'c'}

ts(7053)エラーになる書き方

export function toObjectFromList(list: Hoge[]): {[k: number]: string} | {[k: string]: string} {
  return list.reduce((acc, { id, value }) => {
    acc[id] = value;
    return acc;
  }, {} as {[k: number]: string} | {[k: string]: string});
}
型 'string | number' の式を使用して型 '{ [k: number]: string; } | { [k: string]: string; }' にインデックスを付けることはできないため、要素は暗黙的に 'any' 型になります。
型 'string' のパラメーターを持つインデックス シグネチャが型 '{ [k: number]: string; } | { [k: string]: string; }' に見つかりませんでした。ts(7053)

tsconfig.jsoncompilerOptions"noImplicitAny": true,を指定した場合にエラーになります。

修正

export function toObjectFromList(list: Hoge[]): {[k in string | number]: string} {
  return list.reduce((acc, { id, value }) => {
    acc[id] = value
    return acc;
  }, {} as {[k in string | number]: string});
}	

Playground

0
0
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
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?