[英]Is it possible to extend from any of 'n' defined interfaces and create a new child interface in TypeScript?
I would like to extend from any of 3 defined interfaces and create a new one with its own properties.我想从 3 个定义的接口中的任何一个进行扩展,并创建一个具有自己属性的新接口。
Eg:例如:
interface IChild extends any(IFirst, ISecond, IThird) {
ownVar1: string;
ownVar2: number;
}
Is there any way to achieve this.有什么办法可以做到这一点。
NB I have used any
here as just an example as to show that would like to use some similar keyword if available,请注意,我在这里使用
any
作为示例,以表明希望使用一些类似的关键字(如果可用),
Here is the type you are looking for:这是您正在寻找的类型:
interface A {
a: 'a'
}
interface B {
b: 'b'
}
interface C {
c: 'c'
}
type UnionInterface = A | B | C;
type Child = UnionInterface & {
ownVar1: string;
ownVar2: number;
}
const x: Child = {
ownVar1: 'hello',
ownVar2: 42,
a: 'a'
}
const y: Child = {
ownVar1: 'hello',
ownVar2: 42,
b: 'b'
}
const z: Child = {
ownVar1: 'hello',
ownVar2: 42,
c: 'c'
}
Please keep in mind, that in TS you can do smth like that:请记住,在 TS 中你可以这样做:
interface IChild extends A, B, C {
}
Bit it is mean that your IChild interface extends all properties from A,B,C.这意味着您的 IChild 接口扩展了 A、B、C 的所有属性。
If you want to extend a union type, A or B or C, you should use types
instead interfaces
如果要扩展联合类型 A 或 B 或 C,则应使用
types
而不是interfaces
I am not sure what you want to accomplish.我不确定你想要完成什么。 Maybe you can add some more information about why.
也许您可以添加更多有关原因的信息。 My first thought was that you wanted to use an Interface that is either
IFirst
, ISecond
and so on.我的第一个想法是您想使用
IFirst
、 ISecond
等接口。 Then a function can take any of those as an argument, no matter the type (thus your IChild
).然后 function 可以将其中任何一个作为参数,无论类型如何(因此您的
IChild
)。 If that is the case, I would instead create an IParent
interface and let IFirst
, ISecond
and IThird
extend IParent
如果是这种情况,我会改为创建一个
IParent
接口并让IFirst
、 ISecond
和IThird
扩展IParent
interface IParent{}
interface IFirst extends IParent {}
interface ISecond extends IParent {}
// then do something like this
function foo(IParent myInterface){}
const first: IFirst = {};
const second: ISecond = {};
foo(first); // OK
foo(second); // OK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.