符号 (&) 在 TypeScript 类型定义中是什么意思?

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

this type definition file的第60359行,有如下声明:

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

在这种情况下,& 印记是什么意思?

& 在类型位置表示 intersection 类型。

更多来自 typescript 文档的交叉点类型:

https://www.typescriptlang.org/docs/handbook/2/objects.html#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.

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);
};

Typescript 中的交集类型

  • 类型上下文中 TS 中的 & 表示交集类型。
  • 它将 2 个对象类型的所有属性合并在一起并创建一个新类型

示例:

type dog = {age: number, woof: Function};
type cat = {age: number, meow: Function};

// Type weird is an intersection of cat and dog
// it needs to have all properties of them combined
type weird = dog & cat;

const weirdAnimal: weird = {age: 2, woof: () => {'woof'}, meow: () => {'meow'}}

interface extaprop {
    color: string
}

type catDog = weird & extaprop; // type now also has added color
const weirdAnimal2: catDog = {age: 2, woof: () => {'woof'}, meow: () => {'meow'}, color: 'red'}


// This is different form a union type
// The type below means either a cat OR a dog
type dogOrCat = dog | cat;