TypeScript 3 でクリップボードにコピー機能を実装時に 'select' does not exist が出た時の解決方法

はじめに

TypeScript 3 で textarea の内容をクリップボードにコピーする機能を実装する際に、下記のように JavaScript のコードをそのまま使いました。

sample.ts ※エラーが出る!
const textarea = document.getElementById('my-textarea');
textarea.select();
document.execCommand("copy");

しかし、コンパイル時に下記エラーが出ました。

Property 'select' does not exist on type 'HTMLElement'. Did you mean 'onselect'?

今日はこの解決方法を、エラーが出る理由と併せてご紹介します。
使用した TypeScript のバージョンは 3.5.3 です。

解決方法とエラーになる理由

下記のように getElementById() の結果を HTMLInputElement型にキャストしたところ、エラーは出なくなりました。

sample.ts
const textarea: HTMLInputElement = <HTMLInputElement>document.getElementById('my-textarea');
textarea.select();
document.execCommand("copy");

document.getElementId() の戻り値は HTMLElement 型になります。

しかし HTMLElement には select() が存在しないため前述のエラーが出ます。

select() は HTMLElement を継承した HTMLInputElement に実装されているため、型をキャストすることで対応できます。