rpadovani
rpadovani

Reputation: 7360

Create typescript interface as union of other interfaces

I have a list of interfaces that extends one basic interface.

I have also some functions that can accept any of these interfaces.

I would like to create a new interface that describe that kind of parameter.

So I have something like this:

interface BasicInterface {...};

interface A extends BasicInterface {...};
interface B extends BasicInterface {...};

and I would like something like

interface C = A | B;

I know in my functions I can do

function X(param1: A | B) {};

but since it is more than one function I would like to have just one interface for all of them.

Upvotes: 23

Views: 48029

Answers (2)

GibboK
GibboK

Reputation: 73908

Unfortunatelly you cannot use an interface to define an union type directly.

It is possible to do it only indirectly using a type, for instace:

interface A {
    x: 'x';
}
interface B {
    y: 'y';
}

type C = A | B; // Union of interfaces using a type

More information and example on this page: TypeScript Book

Upvotes: 4

rpadovani
rpadovani

Reputation: 7360

So, after some digging in the Typescript documentation I've found what I was looking for: type aliases.

I can declare a new type like type C = A | B;

Then in function I use type guards to access the right thing:

function isA(param: C): param is A {
    return param.type === A;
}

function X(param1: C) {
  if (isA(param1)) //things related to A
  else //things related to B
};

Upvotes: 35

Related Questions