Express接口包含TypeScript中两个树状对象的公共属性

问题描述

假设我们有两个接口AB

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为什么不执行您想要的操作:

例如,如果库用户想要指定适用于项目数组中所有对象的通用属性,而不必将这些属性合并到每个项目的配置中。

这很有道理。对于从ABAB的获取方式,这并不是一个真正的答案,但是FWIW我通常会从另一个方向着手:定义AB,然后使用extends创建AB,如下所示:

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;
   };
}

我认为尝试从AB开始并仅保留公共部分,特别是递归地保留(对于label)将非常复杂...