TypeScript
  • Introduction
  • Introduction
    • What is TypeScript?
    • Why TypeScript?
    • Setup
  • Beginner
    • Basic types
      • Primitive types
      • Arrays and tuples
      • Enums
      • Any type
    • Objects
    • Type aliases
    • Interfaces
    • Functions
      • Function signatures
      • Void type
      • Functions as types
    • Union types
    • Type guards
    • Intersection types
    • Nullable types
    • Inference
  • Resources
    • Resources
Powered by GitBook
On this page
  1. Beginner

Intersection types

PreviousType guardsNextNullable types

Last updated 6 years ago

Just as allow us to combine multiple types by using the | operator, so do intersection types via the & operator. An intersection between two or more types means that the transpiler is expecting the combined properties of all of the types being intersected. Say we want to create an authenticated user using the information found in a variable typed User and one typed AuthToken. Let's start with two interfaces defining the two types:

interface User {
  name: string;
}

interface AuthToken {
  uuid: string;
}

Now let's create two variables of those types:

const user: User = {
  name: 'Jane Doe',
}

const token: AuthToken = {
  uuid: '98f87b62-58cd-4146-9af9-d15ca8092217',
}

Finally, let's create a function that takes these vars as its arguments and whose return value is an intersection of the two types:

function authenticatedUser(user: User, authAuthToken: AuthToken): User & AuthToken {
  let authedUser: User & AuthToken = {
    name: user.name,
    uuid: authAuthToken.uuid,
  };
  return authedUser;
}

const authedUser = authenticatedUser(user, token);

Note how we use the & in the return portion of the function's definition to tell TypeScript that we want the returned value to be an intersection of both User and AuthToken.

If we need to reuse this intersection in different places, we can save a bit of typing by assigning it to a named type like so:

type AuthedUser = User & Token;

And then using the newly created type instead of manually writing the intersection out:

function authenticatedUser(user: User, authToken: AuthToken): AuthedUser {
  // ...
}
union types