与号 (&) 在 TypeScript 类型定义中是什么意思? [英] What does the ampersand (&) mean in a TypeScript type definition?

查看:24
本文介绍了与号 (&) 在 TypeScript 类型定义中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在线 60359 的 此类型定义此类型定义a>,有如下声明:

On line 60359 of this type definition file, there is the following declaration:

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

& 在这种情况下是什么意思?

What does the & sigil mean in this context?

推荐答案

& in a type position 表示 intersection type.

& in a type position means intersection type.

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

引用上面链接的文档:

交集类型与联合类型密切相关,但它们的使用方式非常不同.交集类型将多种类型合二为一.这允许您将现有类型添加在一起以获得具有您需要的所有功能的单一类型.例如,人 &可序列化 &Loggable 是一种类型,它包含 Person 和 Serializable 和 Loggable.这意味着这种类型的对象将拥有所有三种类型的所有成员.

Intersection types are closely related to union types, but they are used very differently. An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. For example, Person & Serializable & Loggable is a type which is all of Person and Serializable and Loggable. That means an object of this type will have all members of all three types.

例如,如果您的网络请求具有一致的错误处理,那么您可以将错误处理分离为它自己的类型,该类型与对应于单个响应类型的类型合并.

For example, if you had networking requests with consistent error handling then you could separate out the error handling into it’s own type which is merged with types which correspond to a single response type.

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

这篇关于与号 (&amp;) 在 TypeScript 类型定义中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆