简体   繁体   English

ES6语法解构对象+实现接口

[英]ES6 syntax destructuring object + implements interface

I'm going through a code base and ran into complex syntax我正在浏览代码库并遇到复杂的语法

return json?.result?.map(
({ text: label, value }: { text: string; value: any }) => ({
    label,
    value,
}),
);

I understand vaguely (correct me if I'm wrong) something like我模糊地理解(如果我错了,请纠正我)类似

For each result from the json object, run a function that takes in an object as a param and returns another object.对于来自json对象的每个结果,运行一个函数,该函数接受一个对象作为参数并返回另一个对象。

The param implements an interface with this : { text: string; value: any }该参数实现了一个接口: { text: string; value: any } : { text: string; value: any }

I don't understand what's going on here though { text: label, value } .尽管{ text: label, value }我不明白这里发生了什么。 label is not a variable declared anywhere. label不是在任何地方声明的变量。

{ text: label, value } is a destructuring assignment and doesn't really have anything to do with typescript. { text: label, value }是一个解构赋值,与打字稿没有任何关系。 It takes some object and binds its key 'value' to a local variable named value and its key 'text' to some local variable named 'label'.它接受一些对象并将其键“value”绑定到名为 value 的局部变量,并将其键“text”绑定到某个名为“label”的局部变量。

For example:例如:

const testObj = {
    text: "text",
    value: "value"
}

const printTestObj = ({ text: label, value }) => {
    console.log("label = " + label)
    console.log("value = " + value)
}

printTestObj(testObj)

This feature is referred to as property renaming in the TypeScript Handbook and is an advanced form of object destructuring.此功能在TypeScript 手册中称为属性重命名,是对象解构的高级形式。

Your assessment of the structure of json is correct and it's type appears to be Optional<{result?: {text: string, value: any}[]}> .您对json结构的评估是正确的,它的类型似乎是Optional<{result?: {text: string, value: any}[]}> Thus the ReturnType of the function containing the above fragment is Optional<{label: string, value: any}[]> .因此,包含上述片段的函数的ReturnTypeOptional<{label: string, value: any}[]>

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

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