如何解决Express接口包含TypeScript中两个树状对象的公共属性
假设我们有两个接口A
和B
:
interface A {
width: number;
height: number;
label: {
text: string;
};
navigator: {
min: number;
max: number;
}
}
interface B {
width: number;
height: number;
label: {
text: string;
formatter: (text: string) => string;
};
radius: number;
}
我可以手动指定所需的通用形状,如下所示:
interface AB { // ??
width: number;
height: number;
label: {
text: string;
};
}
但是理想情况下,我希望类型系统像这样自动找出形状:
type AB = A & B; // ??
很显然,type AB
的形状不是interface AB
。
有什么想法吗?
编辑:一个示例用例:
const defaultTheme: AB = {
common: { // default values for properties common to A and B
width: 800,height: 400,label: {
text: 'Title'
}
},A: { // missing defaults will come from `common`
navigator: {
min: 0,max: 1
}
},B: { // missing defaults will come from `common`
label: {
formatter: (text: string) => '$' + text
},radius: 50
}
};
// The user would configure a component in a declarative fashion:
const userConfig = {
theme: defaultTheme,items: [{
type: 'A',height: 600,navigator: {
min: 0.5
}
},{
type: 'B',label: {
text: 'My Custom Title'
}
}]
}
因此,用户未明确指定的项目属性将来自默认主题。
解决方法
您已在注释中给出了一个示例用法,解释了A & B
为什么不执行您想要的操作:
例如,如果库用户想要指定适用于项目数组中所有对象的通用属性,而不必将这些属性合并到每个项目的配置中。
这很有道理。对于从A
和B
到AB
的获取方式,这并不是一个真正的答案,但是FWIW我通常会从另一个方向着手:定义AB
,然后使用extends
创建A
和B
,如下所示:
interface AB {
width: number;
height: number;
label: {
text: string;
};
}
interface A extends AB {
navigator: {
min: number;
max: number;
}
}
interface B extends AB {
label: {
text: string;
formatter: (text: string) => string;
};
}
我认为尝试从A
和B
开始并仅保留公共部分,特别是递归地保留(对于label
)将非常复杂...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。