TypeScript中如何为外部库类型添加属性并合并自定义类型
如何为外部库的TypeScript类型添加新属性?
假设外部库中有如下类型定义:
export declare type CreateProductInput = { title: string; }
想要给这个类型添加subtitle属性时,两种常见尝试都会失效:
直接在本地
index.d.ts重新定义类型:export declare type CreateProductInput = { subtitle: string; }这种方式只会创建一个局部类型,完全不会关联外部库的原有类型,因此无效。
在模块声明中用同名interface扩展:
declare module '@path/to/library/type/file' { declare interface CreateProductInput { subtitle: string; } }由于原类型是类型别名(type),而非interface,这种写法会直接覆盖原类型,导致丢失
title字段。
正确解决方案
因为TypeScript不支持类型别名的自动合并,需要通过交叉类型在模块扩展中重新导出合并后的类型:
declare module '@path/to/library/type/file' { // 导入原类型并命名别名避免冲突 import type { CreateProductInput as OriginalInput } from '@path/to/library/type/file'; // 交叉原类型与新属性,重新导出同名类型 export type CreateProductInput = OriginalInput & { subtitle: string; }; }
也可以省略导入步骤,直接通过typeof引用原类型:
declare module '@path/to/library/type/file' { export type CreateProductInput = typeof CreateProductInput & { subtitle: string; }; }
注意事项
- 确保
index.d.ts被包含在tsconfig.json的include配置中,让TypeScript能识别到这个声明文件。 - 模块路径
@path/to/library/type/file必须和外部库导出该类型的实际路径完全匹配,包括文件名和扩展名(如果类型文件有明确扩展名的话)。
内容的提问来源于stack exchange,提问作者Nightwolf
相关产品推荐
相关产品推荐

