This page has been deprecated
This handbook page has been replaced,go to the new page
Unions and Intersection Types
So far, the handbook has covered types which are atomic objects.However, as you model more types you find yourself looking for tools which let you compose or combine existing types instead of creating them from scratch.
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 anumber or astring.For instance, take the following function:
tsTry/*** Takes a string and adds "padding" to the left.* If 'padding' is a string, then 'padding' is appended to the left side.* If 'padding' is a number, then that number of spaces is added to the left side.*/functionpadLeft (value :string,padding :any) {if (typeofpadding ==="number") {returnArray (padding +1).join (" ") +value ;}if (typeofpadding ==="string") {returnpadding +value ;}thrownewError (`Expected string or number, got '${typeofpadding }'.`);}padLeft ("Hello world",4);// returns " Hello world"
The problem withpadLeft in the above example is that itspadding parameter is typed asany.That means that we can call it with an argument that’s neither anumber nor astring, but TypeScript will be okay with it.
tsTry// passes at compile time, fails at runtime.letindentedString =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 ofpadLeft 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.
Instead ofany, we can use aunion type for thepadding parameter:
tsTry/*** Takes a string and adds "padding" to the left.* If 'padding' is a string, then 'padding' is appended to the left side.* If 'padding' is a number, then that number of spaces is added to the left side.*/functionpadLeft (value :string,padding :string |number) {// ...}letArgument of type 'boolean' is not assignable to parameter of type 'string | number'.2345Argument of type 'boolean' is not assignable to parameter of type 'string | number'.indentedString =padLeft ("Hello world",true );
A union type describes a value that can be one of several types.We use the vertical bar (|) to separate each type, sonumber | string | boolean is the type of a value that can be anumber, astring, or aboolean.
Unions with Common Fields
If we have a value that is a union type, we can only access members that are common to all types in the union.
tsTryinterfaceBird {fly ():void;layEggs ():void;}interfaceFish {swim ():void;layEggs ():void;}declarefunctiongetSmallPet ():Fish |Bird ;letpet =getSmallPet ();pet .layEggs ();// Only available in one of the two possible typesProperty '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'.pet .(); swim
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 typeA | B, we only know forcertain that it has members that bothAandB have.In this example,Bird has a member namedfly.We can’t be sure whether a variable typed asBird | Fish has afly method.If the variable is really aFish at runtime, then callingpet.fly() will fail.
Discriminating Unions
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.
tstypeNetworkLoadingState = {state:"loading";};typeNetworkFailedState = {state:"failed";code:number;};typeNetworkSuccessState = {state:"success";response: {title:string;duration:number;summary:string;};};// Create a type which represents only one of the above types// but you aren't sure which it is yet.typeNetworkState =|NetworkLoadingState|NetworkFailedState|NetworkSuccessState;
All of the above types have a field namedstate, and then they also have their own fields:
NetworkLoadingState | NetworkFailedState | NetworkSuccessState |
|---|---|---|
| state | state | state |
| code | response |
Given thestate field is common in every type insideNetworkState - it is safe for your code to access without an existence check.
Withstate as a literal type, you can compare the value ofstate 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 aswitch statement to narrow down which type is represented at runtime:
tsTrytypeNetworkState =|NetworkLoadingState |NetworkFailedState |NetworkSuccessState ;functionlogger (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 errorProperty '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'.state .; code // By switching on state, TypeScript can narrow the union// down in code flow analysisswitch (state .state ) {case"loading":return"Downloading...";case"failed":// The type must be NetworkFailedState here,// so accessing the `code` field is safereturn`Error${state .code } downloading`;case"success":return`Downloaded${state .response .title } -${state .response .summary }`;}}
Union Exhaustiveness checking
We would like the compiler to tell us when we don’t cover all variants of the discriminated union.For example, if we addNetworkFromCachedState toNetworkState, we need to updatelogger as well:
tsTrytypeNetworkFromCachedState = {state :"from_cache";id :string;response :NetworkSuccessState ["response"];};typeNetworkState =|NetworkLoadingState |NetworkFailedState |NetworkSuccessState |NetworkFromCachedState ;functionlogger (s :NetworkState ) {switch (s .state ) {case"loading":return"loading request";case"failed":return`failed with code${s .code }`;case"success":return"got response";}}
There are two ways to do this.The first is to turn onstrictNullChecks and specify a return type:
tsTryfunctionFunction lacks ending return statement and return type does not include 'undefined'.2366Function lacks ending return statement and return type does not include 'undefined'.logger (s :NetworkState ):string {switch (s .state ) {case"loading":return"loading request";case"failed":return`failed with code${s .code }`;case"success":return"got response";}}
Because theswitch is no longer exhaustive, TypeScript is aware that the function could sometimes returnundefined.If you have an explicit return typestring, then you will get an error that the return type is actuallystring | undefined.However, this method is quite subtle and, besides,strictNullChecks does not always work with old code.
The second method uses thenever type that the compiler uses to check for exhaustiveness:
tsTryfunctionassertNever (x :never):never {thrownewError ("Unexpected object: " +x );}functionlogger (s :NetworkState ):string {switch (s .state ) {case"loading":return"loading request";case"failed":return`failed with code${s .code }`;case"success":return"got response";default:returnArgument of type 'NetworkFromCachedState' is not assignable to parameter of type 'never'.2345Argument of type 'NetworkFromCachedState' is not assignable to parameter of type 'never'.assertNever (); s }}
Here,assertNever checks thats is of typenever — the type that’s left after all other cases have been removed.If you forget a case, thens will have a real type and you will get a type error.This method requires you to define an extra function, but it’s much more obvious when you forget it because the error message includes the missing type name.
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 ofPersonandSerializableandLoggable.That means an object of this type will have all members of all three types.
For example, if you had networking requests with consistent error handling then you could separate out the error handling into its own type which is merged with types which correspond to a single response type.
tsTryinterfaceErrorHandling {success :boolean;error ?: {message :string };}interfaceArtworksData {artworks : {title :string }[];}interfaceArtistsData {artists : {name :string }[];}// These interfaces are composed to have// consistent error handling, and their own data.typeArtworksResponse =ArtworksData &ErrorHandling ;typeArtistsResponse =ArtistsData &ErrorHandling ;consthandleArtistsResponse = (response :ArtistsResponse )=> {if (response .error ) {console .error (response .error .message );return;}console .log (response .artists );};
The TypeScript docs are an open source project. Help us improve these pagesby sending a Pull Request ❤
Last updated: Nov 25, 2025