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;
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.
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) .
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 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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With