Reactに外部スクリプトを組み込み、型付けする

<script src="https://example.com/foo.js" /> みたいなのを使う方法

確認環境

Env Ver
React 17.0.2
TypeScript 4.3.2

サンプルコード

  1. public/index.html に読み込み用の <script src="https://example.com/foo.js" /> を追加する
    1. Next.js の場合は <Head /> の中に仕込めば使える
  2. プロジェクトルートに @types/ を作る
  3. @types/Window.d.ts を作り、interface Window の中に使いたい型を定義する

declare global {
  interface Window {
    // props here
  }
}

備考

  • 型定義ファイルの配置先は tsconfig.json で指定できるため、その場合はプロジェクトルートの @types/ 以外でも良い
  • 別にファイル名が Window.d.ts である必要もなく、分れば別になんでもいい