在TypeScript类型定义中,“&”号是什么意思?


Answers:


65

&类型位置是指交叉点类型。

更多

https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types

来自上面链接的文档的引文:

交叉点类型与联合类型紧密相关,但是使用方式却大不相同。相交类型将多种类型组合为一种。这使您可以将现有类型加在一起,以获得具有所需所有功能的单个类型。例如,“ Person&Serializable&Loggable”是“ Person&Serializable and 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);
};

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.