我在外部库中有一个类型,看起来像这样:
export declare type CreateProductInput = {
title: string;
}
我想让这个类型有另一个属性,所以我试着在我自己的index.d.ts
文件中添加它:
我已经试过了:
export declare type CreateProductInput = {
subtitle: string;
}
但这不起作用。我还尝试了以下操作:
declare module '@path/to/library/type/file' {
declare interface CreateProductInput {
subtitle: string;
}
}
但是,这样做会完全覆盖该类型,并且我不再能够访问title
字段。
可以像这样合并类型吗?基本上,我想通过添加另一个属性来修改原始类型。
如果你真的想坚持使用type
,那么你应该能够做到这一点,即使是在导入的类型:
type a = {
title: string
}
type b = a & {
subtitle: string
}
const c: b = {
title: "title",
subtitle: "subtitle"
}
console.log(c)
另一个选择是使用接口:
type d = {
title: string
}
interface e extends d {
subtitle: string
}
const f: e = {
title: "title",
subtitle: "subtitle"
}
console.log(f)
在操场上检查。你想要做的覆盖类型的方式,你试图这样做是不可能的,是糟糕的形式。创建一个包含所需内容的新类型/接口
不幸的是,类型别名不能合并。这是与TypeScript中的接口声明的区别之一。
但是您可以创建一个新的接口,使扩展类型,尽管这似乎不是您想要的:
type CreateProductInput = {
title: string;
}
interface CreateProductInput2 extends CreateProductInput {
subtitle: string;
}
declare const test: CreateProductInput2;
test.title; // Okay
test.subtitle;
操场上联系
要了解更多细节,请参见TypeScript中的接口与类型。