typescript - Typescript:如何扩展具有相同字段的接口
问题描述
我有两个要扩展的打字稿接口,它们都有一个classes
不兼容的字段。
接口“道具”不能同时扩展类型“{类:记录;innerRef?: ((instance: any) => void) | 参考对象 | 空 | 不明确的; }' 和 'TypographyProps'。类型为'{ classes: Record; 的命名属性'classes' innerRef?: ((instance: any) => void) | 参考对象 | 空 | 不明确的; }' 和 'TypographyProps' 不相同。
我该如何扩展这些?我可以选择其中一个或只是重命名其中一个吗?
interface Props extends WithStyles<typeof styles>, TypographyProps {
children: string;
}
解决方案
TypeScript 允许一个名为Mixins的功能,它看起来就像你基本上在做的事情。这将允许您访问多个类。但是,您必须在两个地方创建定义。正如您所看到的,它必须在两者中定义所有类型,但我们不需要将逻辑添加到函数中,只需添加名称和返回类型c
。a
b
c
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]
});
});
}
推荐阅读
- python - 使用具有分隔符的 csv 文件
- python - 熊猫将字符串的类别转换为数字作为一个对象,但得到了一个数字数组
- html - 和 有什么区别?
- php - 在 Zencart 中结帐后无法访问网站
- excel - Excel 公式帮助 - 如果条件为真,则有条件复制/过去
- c# - Gleamtech DocumentUltimate 缓存文件路径
- node.js - 如何从 ReactJS 中的任何 url 获取元数据(图像、标题、描述)
- docker - 使用 Docker 的 ElasticSearch - 启用匿名访问
- opengl - 找出绘制了哪些三角形 OpenGL
- c# - 使用 Bouncy Castle 在 C# 中加密和使用 AES(EAX 模式)在 Python 中解密的问题