简体   繁体   English

是否可以从任何“n”个定义的接口扩展并在 TypeScript 中创建一个新的子接口?

[英]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.我的第一个想法是您想使用IFirstISecond等接口。 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接口并让IFirstISecondIThird扩展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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM