TypeScript中如何重写已实例化导出对象的接口?
问题解决:扩展接口后已实例化对象无法识别新增属性
问题原因
你扩展IExample接口后,@example/core中导出的example常量类型是定义时确定的原始IExample,TypeScript不会自动将已存在变量的类型更新为扩展后的接口。
解决方法
方法1:类型断言(快速临时解决)
使用类型断言将example强制转为扩展后的IExample类型:
import { example, IExample } from '@example/core'; declare module '@example/core' { interface IExample { name?: string; } } // 用类型断言绕过类型检查 console.log((example as IExample).name);
方法2:重新声明模块中的example类型(推荐)
在扩展接口的同时,重新声明example的类型为扩展后的IExample,这样整个包上下文里example都会自动识别新增属性:
import { IExample } from '@example/core'; declare module '@example/core' { interface IExample { name?: string; } // 重新声明example的类型为扩展后的接口 export const example: IExample; } // 现在无需断言,直接访问name属性 console.log(example.name);
方法3:修改@example/core包(若有权限)
如果能修改核心包的代码,去掉example的显式类型标注,让TypeScript自动推导类型,后续扩展接口时会更灵活:
// @example/core interface IExample { id: number; } // 去掉显式类型标注,让类型自动推导 const example = { id: 1 }; export { example, IExample };
之后在扩展包中使用方法2的重新声明方式,即可正常访问新增属性。
内容的提问来源于stack exchange,提问作者Mateusz
相关产品推荐
相关产品推荐

