Intersection and Union types are one of the ways in which you can compose types.
Union Types
Occasionally, you’ll run into a library that expects a parameter to be either a or a string
. For instance, take the following function:
The problem with padLeft
in the above example is that its padding
parameter is typed as any
. That means that we can call it with an argument that’s neither a number
nor a string
, but TypeScript will be okay with it.
ts// passes at compile time, fails at runtime.
let
indentedString =padLeft ("Hello world", true);
In traditional object-oriented code, we might abstract over the two types by creating a hierarchy of types. While this is much more explicit, it’s also a little bit overkill. One of the nice things about the original version of padLeft
was that we were able to just pass in primitives. That meant that usage was simple and concise. This new approach also wouldn’t help if we were just trying to use a function that already exists elsewhere.
A union type describes a value that can be one of several types. We use the vertical bar (|
) to separate each type, so number | string | boolean
is the type of a value that can be a number
, a string
, or a boolean
.
If we have a value that is a union type, we can only access members that are common to all types in the union.
tsinterface
Bird {
fly (): void;
layEggs (): void;}
interface
Fish {
swim (): void;
layEggs (): void;}
declare function
getSmallPet ():Fish |Bird ;let
pet =getSmallPet ();
pet .layEggs ();// Only available in one of the two possible types
pet .(); swim Property 'swim' does not exist on type 'Bird | Fish'.
Property 'swim' does not exist on type 'Bird'.2339Property 'swim' does not exist on type 'Bird | Fish'.
Property 'swim' does not exist on type 'Bird'.
Union types can be a bit tricky here, but it just takes a bit of intuition to get used to. If a value has the type A | B
, we only know for certain that it has members that both A
and B
have. In this example, Bird
has a member named fly
. We can’t be sure whether a variable typed as has a fly
method. If the variable is really a Fish
at runtime, then calling pet.fly()
will fail.
A common technique for working with unions is to have a single field which uses literal types which you can use to let TypeScript narrow down the possible current type. For example, we’re going to create a union of three types which have a single shared field.
Given the state
field is common in every type inside NetworkState
- it is safe for your code to access without an existence check.
With state
as a literal type, you can compare the value of state
to the equivalent string and TypeScript will know which type is currently being used.
NetworkLoadingState | NetworkFailedState | NetworkSuccessState |
---|---|---|
“loading” | “failed” | “success” |
In this case, you can use a switch
statement to narrow down which type is represented at runtime:
tstype
NetworkState =|
NetworkLoadingState |
NetworkFailedState function
networkStatus (state :NetworkState ): string {// Right now TypeScript does not know which of the three
// potential types state could be.
// Trying to access a property which isn't shared
// across all types will raise an error
state .; code Property 'code' does not exist on type 'NetworkState'.
Property 'code' does not exist on type 'NetworkLoadingState'.2339Property 'code' does not exist on type 'NetworkState'.
Property 'code' does not exist on type 'NetworkLoadingState'.
// By switching on state, TypeScript can narrow the union
// down in code flow analysis
switch (
state .state ) {case "loading":
return "Downloading...";
case "failed":
// The type must be NetworkFailedState here,
// so accessing the `code` field is safe
case "success":
return `Downloaded ${
state .response .title } - ${state .response .summary }`;}
}
Intersection Types
Intersection types are closely related to union types, but they are used very differently. An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. For example, Person & Serializable & Loggable
is a type which is all of Person
and Serializable
and Loggable
. That means an object of this type will have all members of all three types.
Intersections are used to implement the :
tsclass
Person {constructor(public
name : string) {}}
interface
Loggable {}
class
ConsoleLogger implementsLoggable {
log (name : string) {
console .log (`Hello, I'm ${name }.`);}
}
// Takes two objects and merges them together
function
extend <First extends {},Second extends {}>(
first :First ,
second :Second ):
First &Second {const
result :Partial <First &Second > = {};for (const
prop infirst ) {if (
first .hasOwnProperty (prop )) {(
result asFirst )[prop ] =first [prop ];}
}
for (const
prop insecond ) {if (
second .hasOwnProperty (prop )) {(
result asSecond )[prop ] =second [prop ];}
}
return
result asFirst &Second ;}
jim .log (jim .name );