在打字稿中使用spread运算符

时间:2018-02-14 13:09:26

标签: javascript typescript ecmascript-next

我想写一个函数,它返回一个包含在另一个组件中的组件。我尝试编写的函数如下所示。

function GetGroup({ name, text, isRequired, ...props }) 

此处,nametextisRequired是从传递的参数中获取的,而其他组件则以props的形式发送到另一个组件。

如何用TypeScript编写它?

2 个答案:

答案 0 :(得分:5)

首先,Object Rest / Spread是一个提议的ECMAScript功能,它正在逐步实现标准化,已达到阶段4 and is in the process of being formally adopted

正如您从其用法中所知,它使得使用纯JavaScript对象非常灵活。

TypeScript 2.1文档中提供了有关该功能输入的信息。正如它非常雄辩地说:

  

对象休息是对象扩展的双重性,因为它们可以提取在解构元素时不会被拾取的任何额外属性:

实际上,实际上有两个功能正在发挥作用,一个功能与另一个功能相辅相成。

对象休息

当使用该功能的 Rest 部分时,它通过使我们能够将其余属性收集到由它们组成的新对象中来增强对象解构。

我们可以像任何其他值一样编写类型注释。例如

interface GroupProperties {
  name: string;
  text: string;
  isRequired?: boolean;
  values: string[];
  flagged: boolean;
}

function Group({ name, text, isRequired, ...rest }: GroupProperties) {
  console.log(rest);
}

这会通知类型系统nametext类型为stringis required类型为boolean。 此外,类型系统知道rest分别具有两个属性valuesflagged类型booleanstring。推导出rest的类型。

对象差价

当使用该特征的 Spread 部分时,它通过从多个源启用对象的声明性构造,轻松创建衍生物,以及轻松取消定义和覆盖来增强对象构造。

类型系统也理解Spread表达式的含义并推断它们评估的类型。

const o = {x: 1, y: 'hello'};

const o1 = {
  ...o,
  y: 1
};

在上面,o1的类型为{x: number, y: number}

答案 1 :(得分:0)

function GetGroup({ name, text, isRequired, ...props }: { name: string; text: string; isRequired: boolean; other: number; arg: string }) {
  props.other // number
  props.arg // string
}

TypeScript只是添加类型..而nametextisRequired是正常参数。另一方面,props是其余的论点。因此,无论剩下的参数如何,都假定为其余的声明类型。

相关问题