18
23

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 1 year has passed since last update.

TS2339エラーの対処方法について

Last updated at Posted at 2022-05-19

エラー

試しにこのようなコードをTypeScriptで書いてみます。

const canvas = document.getElementById("hogeCanvas");
const ctx = canvas.getContext("2d");

JavaScriptでは問題ないが、TypeScriptだと以下のようにエラーとして怒られます。

error TS2339: Property 'getContext' does not exist on type 'HTMLElement'

これはTypeScriptが戻り値をHTMLElementと推論した結果、
getContextのような、メソッドやプロパティが参照できないためです。

解決策

型アサーションで具体的な要素を指定します。

const canvas = <HTMLCanvasElement>document.getElementById("hogeCanvas");
const ctx = canvas.getContext("2d");

もしくは、

const canvas = document.getElementById("hogeCanvas") as HTMLCanvasElement;
const ctx = canvas.getContext("2d");

それかanyです。

const canvas:any = document.getElementById("hogeCanvas");
const ctx = canvas.getContext("2d");

型安全性を妥協するから、anyはあくまで最終手段にしましょう。

参考

18
23
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
18
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?