如何在TypeScript中将类声明为全局类型?避免重复定义接口
解决TypeScript全局类作为类型使用的报错问题
在将类声明为全局类型时,实例化类可以正常运行,但将类作为类型使用时出现错误:'A' refers to a value, but is being used as a type here. Did you mean 'typeof A'?。问题根源在于全局声明中仅定义了类的值类型(构造函数),未将类的实例类型暴露到全局类型空间。
方案一:利用InstanceType关联实例类型
修改lib.ts代码,在全局声明中同时定义值的类型和实例类型:
export {} // 先定义类的实现 class A { hi(): void { console.log('hi') } } declare global { // 声明全局值A,类型为类的构造函数 var A: typeof A; // 声明全局类型A,对应类的实例类型 type A = InstanceType<typeof A>; } // 挂载到全局对象 declare let global: any if (typeof window === 'undefined') global.window = global window.A = A
方案二:全局声明类接口+分离实现
在全局作用域中直接声明类的接口(作为实例类型),再实现具体逻辑并挂载到全局:
export {} declare global { // 全局声明类的接口(作为实例类型) class A { hi(): void; } // 声明全局值A的类型为类的构造函数 var A: typeof A; } // 实现类的具体逻辑 class AImpl implements A { hi(): void { console.log('hi') } } // 挂载到全局对象 declare let global: any if (typeof window === 'undefined') global.window = global window.A = AImpl
验证效果
修改后app.ts中的代码即可正常运行,无论是实例化A还是将A作为类型使用都不会报错:
import './lib.ts' new A().hi() // 正常运行 interface Some { a: A // 不再报错 }
内容的提问来源于stack exchange,提问作者Alex Craft
相关产品推荐
相关产品推荐

