React
와 타입스크립트
환경에서 window
객체 사용시 타입 오류가 발생해 해결법 작성
src
폴더 안에 globals.d.ts
파일을 만들어 속정 정의// src/types/globals.d.ts
interface Window {
myCustomProperty: string;
myCustomMethod: () => void;
}
src/types/*.ts
파일을 와일드카드로 추가시 해당 폴더 내의 .ts
확장자로 끝나는 파일을 인식{
...
"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;