在TypeScript类型定义中,和符号(&)代表什么意思?

184
此类型定义文件的60359行,有以下声明:
type ActivatedEventHandler = (
    ev: Windows.ApplicationModel.Activation.IActivatedEventArgs 
        & WinRTEvent<any>
) => void;

在这个上下文中,& 符号代表什么意思?

5
交叉类型:http://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types - Nitzan Tomer
1
Intersection Types的新链接:https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types - aderchox
3个回答

176

在类型位置中,&表示交叉类型。

有关交叉类型的更多内容,请参阅 Typescript 文档:

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

引用上述文档:

交叉类型与联合类型密切相关,但它们的使用方式非常不同。交叉类型将多个类型合并为一个类型。这允许您将现有类型相加,以获得具有所有所需功能的单个类型。例如,Person & Serializable & Loggable 是一个既是 Person 又是 Serializable 和 Loggable 的类型。这意味着该类型的对象将具有所有三种类型的所有成员。

例如,如果您有统一的错误处理网络请求,则可以将错误处理分离为自己的类型,并将其与对应于单个响应类型的类型合并。

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

10
文档已移至https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types。 - timiscoding
11
再次移动:https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types该页面介绍了 TypeScript 中的交叉类型,它允许将多个类型组合成一个类型。您可以在此处了解如何使用交叉类型来创建更具表现力和灵活性的类型。 - Leif Jones

52

Typescript中的交叉类型

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

例如:

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;

12
这在技术上不是“交集(intersection)”,而是“并集(union)”,对吗? - ecoe
4
“交集”指的是结果类型,而不是在属性上执行的操作。既属于A类型又属于B类型的对象必须具有A中的所有属性(以便它是A的实例),同时也必须具有B的所有属性(以便它也是B的实例)。换句话说,类型的交集必须具有每个类型属性的并集。同样地,类型的并集将具有这些类型属性的交集。 - Rax Adaam
这似乎类似于“extends”,对吗? - Embedded_Mugs
@Embedded_Mugs 这就像多重继承或多重接口实现 - undefined

3
简单来说,
两种类型之间的&表示您可以访问所有类型的属性。
|表示您只能访问共同于两种类型的属性。

|的定义真的正确吗?它难道不是表示要么...要么吗? - undefined
那是真的,然而在类型合并的情况下,它的行为有点扭曲。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接