PTN
PTN

Reputation: 1692

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.

The param implements an interface with this : { text: string; value: any }

I don't understand what's going on here though { text: label, value }. label is not a variable declared anywhere.

Upvotes: 0

Views: 78

Answers (2)

Kapparu
Kapparu

Reputation: 54

This feature is referred to as property renaming in the TypeScript Handbook and is an advanced form of object destructuring.

Your assessment of the structure of json is correct and it's type appears to be Optional<{result?: {text: string, value: any}[]}>. Thus the ReturnType of the function containing the above fragment is Optional<{label: string, value: any}[]>.

Upvotes: 1

Rubydesic
Rubydesic

Reputation: 3476

{ text: label, value } is a destructuring assignment and doesn't really have anything to do with typescript. 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'.

For example:

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

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

printTestObj(testObj)

Upvotes: 3

Related Questions