Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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;
like image 313
camden_kid Avatar asked Aug 25 '17 13:08

camden_kid


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.

Does TypeScript have union types?

TypeScript allows us to use more than one data type for a variable or a function parameter. This is called union type. Consider the following example of union type. In the above example, variable code is of union type, denoted using (string | number) .

How do you use a union in TypeScript?

TypeScript infers the return type of a function, hence, if a function returns more than one type of data, TypeScript will infer the return type to be a union of all the possible return types. If you wish to assign the function's return value to a variable, type the variable as a union of expected return types.

How do you make a union type from a type alias or interface properties in TypeScript?

How to make a union type from a type alias or interface properties in TypeScript? To make a union type from a type alias or interface properties, you can use the indexed access type syntax and then write the property names to make the union type separated by the union operator symbol ( | ) in TypeScript.


1 Answers

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;
like image 116
Pac0 Avatar answered Oct 03 '22 11:10

Pac0