camden_kid
camden_kid

Reputation: 12813

How to create a type from the union of two interfaces?

Consider the following:

interface Man {
  name: string
}

interface Dog {
  breed: string
}

let manDog: Man | Dog;

Is it possible to create a type ManDog which is the equivalent of Man | Dog so that one could do this:

let manDog: ManDog;

Upvotes: 15

Views: 19491

Answers (2)

Pac0
Pac0

Reputation: 23174

You can use the type keyword (not let) to create a new type an alias for your union type.

https://www.typescriptlang.org/docs/handbook/advanced-types.html

interface Man {
  name: string
}

interface Dog {
  breed: string
}

type ManOrDog = Man | Dog;

To use effectively these union types, don't forget to have a look on type guards, explained in the same documentation link.


EDIT : Why did I replaced new type by alias :

A new type would be another Interface, that you could extend and so on.

You cannot create an Interface that extends the alias created by type.

Also, error messages won't show ManOrDog.

In this case, for a union type, the alias is the only way.

For an intersection type however, you would have the choice between a new type with

interface ManAndDog extends Man, Dog { }

and an alias

type ManAndDog = Man & Dog;

Upvotes: 19

Murat Karagöz
Murat Karagöz

Reputation: 37614

You could use inheritance to achieve it

 interface ManDog extends Man, Dog {}

alternatively as a type like this to have either one of Man or Dog

type ManDog = Man | Dog;

Upvotes: 4

Related Questions