简体   繁体   English

请在TypeScript中解释…运算符

[英]Please explain the … operator in TypeScript

the following tutorial ( https://dojo.io/tutorials/1010_containers_and_injecting_state/ ) contains the code snippet: 以下教程( https://dojo.io/tutorials/1010_containers_and_injecting_state/ )包含代码片段:

在此处输入图片说明

which I don't understand and never saw before. 我不了解,也从未见过。 It looks a little bit the "rest parameters" from TypeScript. 它看起来有点像TypeScript中的“剩余参数”。 What exactly does the "..." mean? “ ...”到底是什么意思? Is there somewhere a documentation? 有文件吗? I could not find anything. 我什么都找不到。

This is the spread operator . 这是点差运算符 It essentially unwraps an object / array you are spreading and puts all of the properties where the spread operator is. 它实质上是解包正在散布的对象/数组,并将所有属性放在散布运算符所在的位置。 A very simple example for objects: 一个非常简单的对象示例:

const a = { foo: 'bar' };
const b = { ...a };

This "spreads" the properties of a inside of the object literal. 这种“扩展”的属性a对象文字的内部。 So think of it as doing two steps: take all properties: 因此,可以将其视为执行两个步骤:获取所有属性:

{ { foo: 'bar' } }

...and remove the object wrapper: ...并删除对象包装器:

{ foo: 'bar' }

The result is that a is equivalent to b . 结果是a等于b

You can use this to copy properties into objects and set defaults 您可以使用它来将属性复制到对象中并设置默认值

const a = { a: 1, b: 2 };
const b = { a: 2, c: 3 };
const c = { a: 0, z: 4, ...a, ...b };

c will be { a: 2, z: 4, b: 2, c: 3 } . c将是{ a: 2, z: 4, b: 2, c: 3 } We can do this in two steps again: 我们可以分两步再次执行此操作:

{ a: 0, z: 4, { a: 1, b: 2 }, { a: 2, c: 3 } }

Now unwrap the inner objects: 现在解开内部对象:

{ a: 0, z: 4, a: 1, b: 2, a: 2, c: 3 }

The last time a property was declared takes precedence, so remove a: 0 and a: 1 . 上次声明属性的时间优先,因此请删除a: 0a: 1

You can do this with arrays too and it works the same: 您也可以使用数组执行此操作,并且工作原理相同:

const a = [2, 3];
const b = [1, ...a];

This will be [1, 2, 3] . 这将是[1, 2, 3] Doing the steps: 执行步骤:

[1, [2, 3] ]

Then unwrap the inner array to get [1, 2, 3] . 然后解包内部数组以获得[1, 2, 3]

Note that when you unwrap you need to unwrap into something, so doing: 请注意,在展开时,您需要将某些内容展开,因此请执行以下操作:

const a = [1, 2, 3]
const b = ...a

This isn't allowed because we can't have b = 1, 2, 3 -- that's just not valid syntax. 不允许这样做,因为我们不能有b = 1, 2, 3这只是无效的语法。 However, it does work for function arguments with arrays. 但是,它确实适用于带有数组的函数参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM