Typescript从多个文件合并接口

Typescript从多个文件合并接口,typescript,Typescript,我有一个名为service.ts的文件,它公开了以下代码: export interface SomeInterface { keyOne: string; } export class TestService<T = SomeInterface> { property: T; } 我还创建了index.d.ts文件,该文件声明了相同的接口SomeInterface,其中包含更多键: export interface SomeInterface { keyTwo: n

我有一个名为
service.ts
的文件,它公开了以下代码:

export interface SomeInterface {
  keyOne: string;
}

export class TestService<T = SomeInterface> {
  property: T;
}
我还创建了
index.d.ts
文件,该文件声明了相同的接口
SomeInterface
,其中包含更多键:

export interface SomeInterface {
  keyTwo: number;
}
问题是
service.property
只“知道”
keyOne
属性。我怎样才能告诉typescript合并它们呢


您需要扩展接口并为其命名

export interface SomeInterface {
  keyOne: string;
}

export interface SomeExtendingInterface extends SomeInterface {
  keyTwo: number;
}
或者将它们合并到具有这两个属性的类型

interface Foo {
    foo: string;
}

interface Bar {
    bar: string;
}

type Baz = Foo & Bar;

const foo: Baz = {
    foo: '',
    bar: ''
};

如果我理解正确(您在@chris p bacon的回答中的评论),您希望从库中扩充模块类型定义。到InTypeScript文档的链接已经是一个很好的捕获。关于第三方库类型扩展,有一些很好的答案:和

例如,如果出于某种原因(比如说
vendor lib.d.ts
而不是
index.d.ts
以使其更清晰),我们希望扩充库模块类型定义,我们可以通过以下方式实现:

供应商-lib.d.ts:

export interface SomeInterface {
  keyTwo: number
}
服务台

// 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
  }
}
index.ts:

const service = new TestService(); service.property = {...};
service.property.keyOne // works
service.property.keyTwo // works

它应该像我根据文档所做的那样工作,不管它是否工作,为什么两个不同的接口会有相同的名称?您不认为在维护代码的几个月内这会让人困惑吗?但是做你喜欢做的事……目的是让使用库的用户能够全局扩展接口。@老实说,你应该在你的问题中添加它作为上下文,否则,它就没有多大意义了。
const service = new TestService(); service.property = {...};
service.property.keyOne // works
service.property.keyTwo // works