どうも、ちょげ(@chogetarou)です。
Objectの操作中に「element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type」と言うエラーが出ました。
なかなかエラーが解決できず、あれこれ検索して、なんとかエラーを解決できました。
「element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type と言うエラーが出た!」
と言う人に向けて、私が解決できた方法を紹介します。
解決方法

「element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type」を解決するには、typeもしくはinterfaceを使います。
まず、typeもしくはinterfaceで、オブジェクトの型を宣言します。
そして、宣言したオブジェクトの型をオブジェクトに設定します。
//typeもしくはinterfaceで型を宣言
type ObjType = {
[key: string]: number
}
//オブジェクトに型を設定
let obj: ObjType = { ・・・ };
オブジェクトの型を設定することで、「element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type」エラーが解決できました。
解決例
エラー発生
let nums = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 };
for (const key in nums) {
if (nums.hasOwnProperty(key)) {
delete nums[key]; //エラー発生!
}
}
console.log(nums)
エラーなし
type Numbers = {
[key: string]: number
}
let nums: Numbers = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 };
for (const key in nums) {
if (nums.hasOwnProperty(key)) {
delete nums[key];
}
}
console.log(nums)
出力:
{}
コメント