我有一个名为service.ts
它公开了以下代码:
export interface SomeInterface {
keyOne: string;
}
export class TestService<T = SomeInterface> {
property: T;
}
In index.ts
文件我正在使用该服务:
import { TestService } from './service';
const service = new TestService();
service.property.keyOne
我还创建了index.d.ts
声明相同接口的文件SomeInterface
有更多键:
export interface SomeInterface {
keyTwo: number;
}
问题是service.property
只“知道”keyOne
财产。我怎样才能告诉打字稿合并它们呢?
https://stackblitz.com/edit/typescript-cp8zmv https://stackblitz.com/edit/typescript-cp8zmv
如果我理解正确(你在 @chris p bacon 的回答中的评论),你想从库中扩充模块类型定义。链接到声明合并 https://www.typescriptlang.org/docs/handbook/declaration-merging.html在 TypeScript 文档中已经是一个很好的收获。关于第三方库类型扩展,有一些很好的答案:here https://stackoverflow.com/questions/43952198/how-to-override-or-extend-a-libary-type-definition-in-typescript and here https://stackoverflow.com/questions/48690619/how-can-i-augment-a-property-within-a-third-party-typescript-interface-defined-a/48692419.
对于您的示例,如果我们出于某种原因想要扩充库模块类型定义(假设vendor-lib.d.ts
而不是你的index.d.ts
为了更清楚),我们可以通过模块增强 https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation:
供应商-lib.d.ts:
export interface SomeInterface {
keyTwo: number
}
服务.ts
// here for simplicity a relative import
import { SomeInterface } from "./vendor-lib"
// Augment above imported module.
// Important: this file must be a module (not a script) via `import/export`.
// Then augmentation will work. Otherwise compiler expects a module declaration.
declare module "./vendor-lib" {
interface SomeInterface {
keyOne: string
}
}
索引.ts:
const service = new TestService(); service.property = {...};
service.property.keyOne // works
service.property.keyTwo // works
堆栈闪电战 https://stackblitz.com/edit/typescript-tzzg8l
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)