3
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.

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type...が出た時に解決した方法

Posted at

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type { ... } ... が出てちょっとハマったので共有します

環境

mac 11.5.2(Big Sur)

vue 2.6.14
typescript 4.3.2
eslint 6.8.0
@vue/eslint-config-typescript 7.0.0

問題

自前で作ったCMSの編集処理でpostするデータが入った連想配列をFormDataに詰め直す際にObject.keys()で連想配列をループしながらvalueを取り出したかったが、当該エラー発生

Typescript
interface Article {
  id: number | null;
  title: string;
  description: string;
  eyecatch: string;
  headline: string;
  paragraph: string;
  links: number[];
}

const postData = reactive<Article>({
  id: null,
  title: "",
  description: "",
  eyecatch: "",
  headline: "",
  paragraph: "",
  links: [],
});

const formData = new FormData();
Object.keys(postData).forEach((key) => {
  formData.append(key, postData[key]);  // postData[key]でTS7053エラー発生
});

原因

上記postData[key]が暗黙的にanyを含んでいるとのこと。ん〜どゆこと?Articleにnullとか配列が入ってるから??上記コードの場合postData['title']などArticleのkeyになっている文字列を直接指定すればエラーは起きない。ということはkeyが指定した文字列でないからか。。ちょっとナニイッテルカワカラナイヨ。Object.keysで回すときってkeyは指定された文字列ちゃうの??

解決

key as keyof Articleでエラーがなくなりました。他の方の記事を参考にさせていただきました。

Object.keys(postData).forEach((key) => {
  formData.append(key, postData[key as keyof Article]);
});

まとめ

ちょっと腑に落ちないエラーはルールから除外してもいいんだけど、それだとtypescript使ってる旨味がないからちゃんと解決していかなきゃいけないけど、このパターンはtypescript側で吸収できるんじゃね?と思ったり思わなかったり。

参考にしたページ

助かりました。ありがとうございます。

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