在 TypeScript 类型定义中,与号(&)意味着什么?

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

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

在这种情况下,&标志意味着什么?

56617 次浏览

类型位置上的 &表示 十字路口类型。

更多关于交叉口类型的文档:

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

类型中的交集类型

  • 在 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;