React타입스크립트 환경에서 window 객체 사용시 타입 오류가 발생해 해결법 작성

타입 선언 파일 생성

// src/types/globals.d.ts

interface Window {
  myCustomProperty: string;
  myCustomMethod: () => void;
}

tsconfig.json 파일에 타입 선언 파일 포함

{
	...
  "include": ["src/types/*.ts"],
  ...
}

window 객체 사용

// src/App.tsx

import React, { useEffect } from "react";

const App: React.FC = () => {
  useEffect(() => {
    window.myCustomProperty = "Hello, world!";
    window.myCustomMethod = () => {
      console.log("This is a custom method on the window object");
    };

    console.log(window.myCustomProperty); // "Hello, world!"
    window.myCustomMethod(); // "This is a custom method on the window object"
  }, []);

  return <div className="App">Check the console for messages</div>;
};

export default App;