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

Car*_*lin 41 types ampersand typescript

此类型定义文件的第60359行,有以下声明:

type ActivatedEventHandler = (ev: Windows.ApplicationModel.Activation.IActivatedEventArgs & WinRTEvent<any>) => void;
Run Code Online (Sandbox Code Playgroud)

&在这种背景下,印记意味着什么?

Wil*_*een 53

Typescript 中的交集类型

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

例子:

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;
Run Code Online (Sandbox Code Playgroud)

  • 从技术上讲,这不是“并集”而不是“交集”吗? (14认同)
  • “交集”是指结果_类型_,而不是对属性执行的操作。同时属于类型 A 和类型 B 的对象必须具有 A 中的所有属性(因此它是 A 的实例),同时还具有 B 的所有属性(因此它也是 B 的实例)。换句话说,类型的交集必须具有每个类型的属性的并集。类似地,类型的并集将具有这些类型的属性的交集。 (5认同)

bas*_*rat 36

&在类型位置意味着类型交集.

更多

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

  • 再次移动:https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types (11认同)
  • 文档移至 https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types (5认同)