TypeScript错误:React应用中类型'Window'上不存在属性'X'
你好!我正在使用create-react-app和TypeScript开发一个React应用。我遇到了一个问题:我试图访问全局属性`window.myCustomProp`,这是我添加到`window`对象中用于与第三方脚本集成的。这是我的代码:
```typescript
// App.tsx
const App: React.FC = () => {
useEffect(() => {
// 设置自定义属性
window.myCustomProp = 'Hello from custom property';
// 尝试读取它
console.log(window.myCustomProp);
}, []);
return
My App
;
};
```
编译时TypeScript报错:
```
Property 'myCustomProp' does not exist on type 'Window & typeof globalThis'.
```
我已经尝试过使用`(window as any).myCustomProp`,但这看起来像是一个临时解决方案。有没有更正确的方法在TypeScript中声明`window`对象上的自定义属性?我使用的是React 18、TypeScript 5.0和最新版本的create-react-app。
非常感谢详细解答!