首页 > 解决方案 > Typescript:如何扩展具有相同字段的接口

问题描述

我有两个要扩展的打字稿接口,它们都有一个classes不兼容的字段。

接口“道具”不能同时扩展类型“{类:记录;innerRef?: ((instance: any) => void) | 参考对象 | 空 | 不明确的; }' 和 'TypographyProps'。类型为'{ classes: Record; 的命名属性'classes' innerRef?: ((instance: any) => void) | 参考对象 | 空 | 不明确的; }' 和 'TypographyProps' 不相同。

我该如何扩展这些?我可以选择其中一个或只是重命名其中一个吗?

interface Props extends WithStyles<typeof styles>, TypographyProps {
   children: string;
}

标签: typescripttypescript-typings

解决方案


TypeScript 允许一个名为Mixins的功能,它看起来就像你基本上在做的事情。这将允许您访问多个类。但是,您必须在两个地方创建定义。正如您所看到的,它必须在两者中定义所有类型,但我们不需要将逻辑添加到函数中,只需添加名称和返回类型cabc

class a {
    public ax: number
}

class b {
    public bx: string
    public by(): void{
        console.log('by()')
    }
}

class c implements a, b { 
    public ax: number = 123
    public bx: string = 'hello'
    public by: () => void
}

然后需要创建 mixin(正如我们从文档中看到的那样)

applyMixins(c, [a, b])

let myobj = new c()
myobj.by()

从文档:

这将遍历每个 mixins 的属性并将它们复制到 mixins 的目标,用它们的实现填充替代属性。

function applyMixins(derivedCtor: any, baseCtors: any[]) {
  baseCtors.forEach(baseCtor => {
    Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
      derivedCtor.prototype[name] = baseCtor.prototype[name]
    });
  });
}

推荐阅读