Skip to content
Advertisement

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.

Advertisement

Answer

{ 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)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement