【问题标题】:What does the ampersand (&) mean in a TypeScript type definition?TypeScript 类型定义中的 & 符号是什么意思?
【发布时间】:2016-11-14 00:44:55
【问题描述】:
this type definition file 的第 60359 行有如下声明:
type ActivatedEventHandler = (ev: Windows.ApplicationModel.Activation.IActivatedEventArgs & WinRTEvent<any>) => void;
& 印记在这种情况下是什么意思?
【问题讨论】:
标签:
types
typescript
ampersand
【解决方案1】:
& 在类型位置表示 intersection 类型。
更多关于交叉点类型的打字稿文档:
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);
};
【解决方案2】:
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;