What does the ampersand (&) mean in a TypeScript type definition?

Carl Patenaude Poulin picture Carl Patenaude Poulin · Jul 12, 2016 · Viewed 26.2k times · Source

On line 60359 of this type definition file, there is the following declaration:

type ActivatedEventHandler = (ev: Windows.ApplicationModel.Activation.IActivatedEventArgs & WinRTEvent<any>) => void;

What does the & sigil mean in this context?

Answer

basarat picture basarat · Jul 12, 2016

& in a type position means intersection type.

More

https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types

Citation from the docs linked above:

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.

interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface ArtworksData {
  artworks: { title: string }[];
}

interface ArtistsData {
  artists: { name: string }[];
}

// These interfaces are composed to have
// consistent error handling, and their own data.

type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;

const handleArtistsResponse = (response: ArtistsResponse) => {
  if (response.error) {
    console.error(response.error.message);
    return;
  }

  console.log(response.artists);
};