前提
TypeScript初心者です。
型のエラーで困っています。
実現したいこと
連想配列の配列からキーと値を渡して、それに合致する要素を返す関数を作りたい。
以下のJSでの例をTSで作りたいのですが、型のエラー起きてしまい、解決できないので、ご助力お願いいたします。
(例)jsでの例
js
1// テスト配列 2const testArray = [ 3 { 4 "targetKey": "あいうえお", 5 "hogehoge": { 6 "foo": "fooあ", 7 "goo": "gooあ" 8 } 9 }, 10 { 11 "targetKey": "かきくけこ", 12 "hogehoge": { 13 "foo": "fooか", 14 "goo": "gooか" 15 } 16 }, 17 { 18 "targetKey": "さしすせそ", 19 "hogehoge": { 20 "foo": "fooさ", 21 "goo": "goさ" 22 } 23 } 24] 25
js
1 2// 目的の関数(js) 3const getElement = (arr, tKey, tVal) => { 4 return arr.filter((ele) => { 5 return ele[tKey] === tVal; 6 })[0]; 7}; 8 9getElement(testArray, 'targetKey', 'あいうえお')
output
1{ 2 hogehoge: { 3 foo: "fooあ", 4 goo: "gooあ" 5 }, 6 targetKey: "あいうえお" 7}
発生している問題・エラーメッセージ
// 行: 3のele[tKey] の部分で 型 'string' の式を使用して型 'unknown' にインデックスを付けることはできないため、要素は暗黙的に 'any' 型になります。 型 'string' のパラメーターを持つインデックス シグネチャが型 'unknown' に見つかりませんでした。ts(7053)
該当のソースコード
ts
1const getElement = <T>(arr: T[], tKey: string, tVal: string): T => { 2 return arr.filter((ele) => { 3 return ele[tKey] === tVal; 4 })[0]; 5};
試したこと
https://solareenlo.com/docs/pl/typescript/
上記ページを参考に以下のようにしてみましたが解決できませんでした。
ts
1const getElement = <S, T extends keyof S>(arr: S[], tKey: T, tVal: string,): S => { 2 return arr.filter((ele) => { 3 return ele[tKey] === tVal; 4 })[0]; 5};
// 行:3 ele[tKey] === tVal 型 'S[T]' と 'string' には重複がないため、この条件は常に 'false' を返します。ts(2367)
補足情報(FW/ツールのバージョンなど)
- vscode
回答2件
あなたの回答
tips
プレビュー