在同一TypeScript文件中使用接口与导出类时出现类型错误
问题原因及解决办法
核心原因
当文件里存在export语句时,TypeScript会把这个文件当作ES模块处理,而非全局脚本:
- 没有
export时,你声明的interface Window属于全局作用域,会自动和TypeScript内置的全局Window类型合并,所以window.Test能被正确识别。 - 加入
export class Person后,文件变成ES模块,此时你声明的interface Window属于模块局部作用域,不会和全局的Window类型合并,TS自然找不到Test这个属性,就抛出了2339错误。
解决办法
方法一:用declare global把接口声明放到全局作用域
修改代码,把扩展Window的接口包裹在declare global块里,强制让它进入全局作用域,即使文件是ES模块也能生效:
declare global { interface Window { Test: string; } } window.Test = "cool"; export class Person { name: string; constructor(name: string) { this.name = name; } print(): void { console.log(this.name); } }
方法二:把全局类型扩展放到单独的声明文件
如果这个Window扩展是项目通用的,可以新建一个.d.ts文件(比如global.d.ts),把接口声明放进去,这个文件会被TS当作全局声明自动加载:
// global.d.ts interface Window { Test: string; }
然后原来的文件保留export类即可:
window.Test = "cool"; export class Person { name: string; constructor(name: string) { this.name = name; } print(): void { console.log(this.name); } }
内容的提问来源于stack exchange,提问作者Kirubachari
相关产品推荐
相关产品推荐

