我有一个名为的文件service.ts,它公开以下代码:
export interface SomeInterface {
keyOne: string;
}
export class TestService<T = SomeInterface> {
property: T;
}
Run Code Online (Sandbox Code Playgroud)
在index.ts文件中,我正在使用该服务:
import { TestService } from './service';
const service = new TestService();
service.property.keyOne
Run Code Online (Sandbox Code Playgroud)
我还创建index.d.ts了SomeInterface用更多键声明相同接口的文件:
export interface SomeInterface {
keyTwo: number;
}
Run Code Online (Sandbox Code Playgroud)
问题是service.property只有“知道”keyOne属性。我怎么能告诉打字稿合并他们两个?
你会扩展接口并给它另一个名字
export interface SomeInterface {
keyOne: string;
}
export interface SomeExtendingInterface extends SomeInterface {
keyTwo: number;
}
Run Code Online (Sandbox Code Playgroud)
或者将它们合并为具有这两个属性的类型
interface Foo {
foo: string;
}
interface Bar {
bar: string;
}
type Baz = Foo & Bar;
const foo: Baz = {
foo: '',
bar: ''
};
Run Code Online (Sandbox Code Playgroud)
如果我理解正确(您在@chris p bacon 的回答中的评论),您希望从库中扩充模块类型定义。TypeScript 文档中声明合并的链接已经很不错了。有一些关于第三方 lib 类型扩展的很好的答案:here和here。
对于您的示例,如果我们出于某种原因想要扩充库模块类型定义(让我们说vendor-lib.d.ts而不是您index.d.ts来使其更清楚),我们可以通过Module Augmentation做到这一点:
供应商-lib.d.ts:
export interface SomeInterface {
keyTwo: number
}
Run Code Online (Sandbox Code Playgroud)
服务.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
}
}
Run Code Online (Sandbox Code Playgroud)
索引.ts:
const service = new TestService(); service.property = {...};
service.property.keyOne // works
service.property.keyTwo // works
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3290 次 |
| 最近记录: |