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 a number or a string. For instance, take the following function:

  1. ts
    /**
  2. * Takes a string and adds "padding" to the left.
  3. * If 'padding' is a string, then 'padding' is appended to the left side.
  4. * If 'padding' is a number, then that number of spaces is added to the left side.
  5. */
  6. function padLeft(value: string, padding: any) {
  7. if (typeof padding === "number") {
  8. return Array(padding + 1).join(" ") + value;
  9. }
  10. if (typeof padding === "string") {
  11. return padding + value;
  12. }
  13. throw new Error(`Expected string or number, got '${padding}'.`);
  14. }
  15. padLeft("Hello world", 4); // returns " Hello world"

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.

  1. ts
    // passes at compile time, fails at runtime.
  2. 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.

Instead of any, we can use a union type for the padding parameter:

  1. ts
    /**
  2. * Takes a string and adds "padding" to the left.
  3. * If 'padding' is a string, then 'padding' is appended to the left side.
  4. * If 'padding' is a number, then that number of spaces is added to the left side.
  5. */
  6. function padLeft(value: string, padding: string | number) {
  7. // ...
  8. }
  9. let indentedString = padLeft("Hello world", true);
  10. Argument of type 'true' is not assignable to parameter of type 'string | number'.2345Argument of type 'true' is not assignable to parameter of type 'string | number'.

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.

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.

  1. ts
    interface Bird {
  2. fly(): void;
  3. layEggs(): void;
  4. }
  5. interface Fish {
  6. swim(): void;
  7. layEggs(): void;
  8. }
  9. declare function getSmallPet(): Fish | Bird;
  10. let pet = getSmallPet();
  11. pet.layEggs();
  12. // Only available in one of the two possible types
  13. pet.swim();
  14. Property 'swim' does not exist on type 'Bird | Fish'.
  15. Property 'swim' does not exist on type 'Bird'.2339Property 'swim' does not exist on type 'Bird | Fish'.
  16. 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 Bird | Fish has a fly method. If the variable is really a Fish at runtime, then calling pet.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.

  1. ts
    type NetworkLoadingState = {
  2. state: "loading";
  3. };
  4. type NetworkFailedState = {
  5. state: "failed";
  6. code: number;
  7. };
  8. type NetworkSuccessState = {
  9. state: "success";
  10. response: {
  11. title: string;
  12. duration: number;
  13. summary: string;
  14. };
  15. };
  16. // Create a type which represents only one of the above types
  17. // but you aren't sure which it is yet.
  18. type NetworkState =
  19. | NetworkLoadingState
  20. | NetworkFailedState
  21. | NetworkSuccessState;

All of the above types have a field named state, and then they also have their own fields:

NetworkLoadingStateNetworkFailedStateNetworkSuccessState
statestatestate
coderesponse

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.

NetworkLoadingStateNetworkFailedStateNetworkSuccessState
“loading”“failed”“success”

In this case, you can use a switch statement to narrow down which type is represented at runtime:

  1. ts
    type NetworkState =
  2. | NetworkLoadingState
  3. | NetworkFailedState
  4. | NetworkSuccessState;
  5. function networkStatus(state: NetworkState): string {
  6. // Right now TypeScript does not know which of the three
  7. // potential types state could be.
  8. // Trying to access a property which isn't shared
  9. // across all types will raise an error
  10. state.code;
  11. Property 'code' does not exist on type 'NetworkState'.
  12. Property 'code' does not exist on type 'NetworkLoadingState'.2339Property 'code' does not exist on type 'NetworkState'.
  13. Property 'code' does not exist on type 'NetworkLoadingState'.
  14. // By switching on state, TypeScript can narrow the union
  15. // down in code flow analysis
  16. switch (state.state) {
  17. case "loading":
  18. return "Downloading...";
  19. case "failed":
  20. // The type must be NetworkFailedState here,
  21. // so accessing the `code` field is safe
  22. return `Error ${state.code} downloading`;
  23. case "success":
  24. return `Downloaded ${state.response.title} - ${state.response.summary}`;
  25. }
  26. }

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.

For example, if you had networking requests with consistent error handling then you could separate out the error handling into it’s own type which is merged with types which correspond to a single response type.

  1. ts
    interface ErrorHandling {
  2. success: boolean;
  3. error?: { message: string };
  4. }
  5. interface ArtworksData {
  6. artworks: { title: string }[];
  7. }
  8. interface ArtistsData {
  9. artists: { name: string }[];
  10. }
  11. // These interfaces are composed to have
  12. // consistent error handling, and their own data.
  13. type ArtworksResponse = ArtworksData & ErrorHandling;
  14. type ArtistsResponse = ArtistsData & ErrorHandling;
  15. const handleArtistsResponse = (response: ArtistsResponse) => {
  16. if (response.error) {
  17. console.error(response.error.message);
  18. return;
  19. }
  20. console.log(response.artists);
  21. };

Mixins via Intersections

Intersections are used to implement the mixin pattern:

  1. ts
    class Person {
  2. constructor(public name: string) {}
  3. }
  4. interface Loggable {
  5. log(name: string): void;
  6. }
  7. class ConsoleLogger implements Loggable {
  8. log(name: string) {
  9. console.log(`Hello, I'm ${name}.`);
  10. }
  11. }
  12. // Takes two objects and merges them together
  13. function extend<First extends {}, Second extends {}>(
  14. first: First,
  15. second: Second
  16. ): First & Second {
  17. const result: Partial<First & Second> = {};
  18. for (const prop in first) {
  19. if (first.hasOwnProperty(prop)) {
  20. (result as First)[prop] = first[prop];
  21. }
  22. }
  23. for (const prop in second) {
  24. if (second.hasOwnProperty(prop)) {
  25. (result as Second)[prop] = second[prop];
  26. }
  27. }
  28. return result as First & Second;
  29. }
  30. const jim = extend(new Person("Jim"), ConsoleLogger.prototype);
  31. jim.log(jim.name);