TypeScript 中的 Window 类型不存在属性

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; } }
代码示例显示了如何使用类型为.namedWindow的属性扩展接口这在您的用例中会有所不同,因此请务必调整属性名称和类型。examplestring

如果您不知道特定属性的类型并希望关闭类型检查,请将其设置为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 个importorexport
语句的文件,因此我们需要这样做才能扩大全局范围。

请注意,您必须根据您的用例更改所提供文件的内容。 index.d.ts

您应该添加您打算在window对象上访问的所有属性的名称(和类型)。

源代码/类型/index.d.ts
export {}; declare global { interface Window { example: string; } }

提供的文件只是添加example一个类型为 的属性string,这很可能不是您需要的。

TypeScript.d.ts在查找常规文件的相同位置查找.ts文件,这由文件中的设置决定 includeexcludetsconfig.json

TypeScript 会将您声明的Window接口与原始
Window接口合并,因此当您使用该window对象时,您将能够从两个接口访问属性。

结论

当我们访问界面上不存在的属性时,会出现“Property does not exist on type ‘Window & typeof globalThis’”错误Window要解决该错误,请Window在文件中扩展接口.d.ts并在对象上添加您打算访问的window属性。