打字稿操作员 [英] Typescript & operator

查看:28
本文介绍了打字稿操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找 TypeScript 中 & 运算符的定义.我最近遇到了以下代码:

I'm struggling to find the definition of the & operator in TypeScript. I have recently come across the following code:

type IRecord<T> = T & TypedMap<T>;

那个运算符有什么作用,它与联合类型|有什么不同?

What does that operator do, and how is it different from the union type |?

推荐答案

这看起来像是来自 Intersection Types 语言规范的一部分.具体来说,& 似乎是一个 交集类型文字.至于它的作用:

This looks like it's from the Intersection Types portion of the Language Specification. Specifically, the & appears to be an intersection type literal. As for what it does:

交集类型表示同时具有多种类型的值.交集类型 A & 的值B 是类型 A 和类型 B 的值.交集类型是使用交集类型文字编写的(第 3.8.7 节).

Intersection types represent values that simultaneously have multiple types. A value of an intersection type A & B is a value that is both of type A and type B. Intersection types are written using intersection type literals (section 3.8.7).

规范继续提供有用的片段以更好地理解行为:

The spec goes on to offer a helpful snippet to better understand the behavior:

interface A { a: number }  
interface B { b: number }

var ab: A & B = { a: 1, b: 1 };  
var a: A = ab;  // A & B assignable to A  
var b: B = ab;  // A & B assignable to B

因为abAB类型,我们可以把它赋值给a 和/或 b.如果ab 只是B 类型,我们只能将它分配给b.

Because ab is both of type A and of type B, we can assign it to a and/or b. If ab were only of type B, we could only assign it to b.

您分享的代码可能来自GitHub上的这条评论,其中提到了Intersection类型.

The code you shared may be from this comment on GitHub, which mentions Intersection Types.

这篇关于打字稿操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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