やりたいこと
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.json
でcompilerOptions
に"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});
}