TypeScript 中的 Window 类型不存在属性
Property does not exist on type Window in TypeScript
当我们访问界面上不存在的属性时,会出现“Property does not exist on type ‘Window & typeof globalThis’”错误Window
。要解决该错误,请Window
在文件中扩展接口.d.ts
并在对象上添加您打算访问的window
属性。
以下是错误发生方式的示例:
索引.ts
// ⛔️ Property 'example' does not exist on // type 'Window & typeof globalThis'.ts(2339) window.example = 'hello'; console.log(window.example);
在您的src
目录中,创建一个types
包含以下
index.d.ts
文件的目录:
源代码/类型/index.d.ts
export {}; declare global { interface Window { example: string; } }
代码示例显示了如何使用类型为.named
Window
的属性扩展接口。这在您的用例中会有所不同,因此请务必调整属性名称和类型。example
string
如果您不知道特定属性的类型并希望关闭类型检查,请将其设置为any
。
源代码/类型/index.d.ts
export {}; declare global { interface Window { example: any; // 👈️ turn off type checking } }
现在我可以设置和访问对象的example
属性window
而不会出现错误。
索引.ts
// ✅ Works now window.example = 'hello'; console.log(window.example);
如果错误仍然存在,请尝试将types
目录路径添加到
tsconfig.json
文件中。
tsconfig.json文件
{ "compilerOptions": { // ... rest "typeRoots": ["./node_modules/@types", "./src/types"] } }
我们使用文件中的export {}
行将index.d.ts
其标记为外部模块。模块是一个包含至少 1 个import
orexport
语句的文件,因此我们需要这样做才能扩大全局范围。
请注意,您必须根据您的用例更改所提供文件的内容。
index.d.ts
您应该添加您打算在window
对象上访问的所有属性的名称(和类型)。
源代码/类型/index.d.ts
export {}; declare global { interface Window { example: string; } }
提供的文件只是添加example
一个类型为 的属性string
,这很可能不是您需要的。
TypeScript
.d.ts
在查找常规文件的相同位置查找.ts
文件,这由文件中的和设置决定。 include
exclude
tsconfig.json
TypeScript 会将您声明的Window
接口与原始
Window
接口合并,因此当您使用该window
对象时,您将能够从两个接口访问属性。
结论
当我们访问界面上不存在的属性时,会出现“Property does not exist on type ‘Window & typeof globalThis’”错误Window
。要解决该错误,请Window
在文件中扩展接口.d.ts
并在对象上添加您打算访问的window
属性。