Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create typescript interface as union of other interfaces

Tags:

typescript

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

like image 323
rpadovani Avatar asked Feb 10 '17 09:02

rpadovani


People also ask

Can you union interface in TypeScript?

TypeScript provides a powerful feature that lets multiple interfaces be combined into a single union type. It means that a function can be called with an argument whose interface is any one of the interfaces in the union type.

Can an interface implement another interface TypeScript?

Just like C# and Java, a TypeScript class can implement multiple interfaces, and to do that, we should use the keyword called implements that allows us to access multiple interfaces into the class implementation.

How do you inherit from another interface in TypeScript?

An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.

How do I create a union in TypeScript?

TypeScript - Union In the above example, variable code is of union type, denoted using (string | number) . So, you can assign a string or a number to it. The function parameter can also be of union type, as shown below. In the above example, parameter code is of union type.


1 Answers

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
};
like image 165
rpadovani Avatar answered Oct 10 '22 12:10

rpadovani