1

I recently saw a code like below

type TestType = {
  foo: string;
};

const Test = ({
    foo: bar,
}) => {
    console.log(bar)
}

Test({foo: "hello world"})

I'm not sure about how foo:bar part works. Does bar automatically point to whatever value passed to key foo? I'd appreciate if someone can let me know what this is called or any other materials I can read. Thank you so much!

Barmar
  • 741,623
  • 53
  • 500
  • 612
kidox
  • 61
  • 1
  • 6
  • That's object destructuring. – Barmar May 19 '21 at 21:24
  • It's not specific to TypeScript (but maybe JavaScript copied it from TypeScript). – Barmar May 19 '21 at 21:25
  • More specifically, it's destructuring with renaming. The `foo` variable is being renamed to `bar` at the time of destructuring, so that it can be referred to as `bar` later in the code. The example you provided doesn't show why that's useful, but it can be quite useful if you're destructuring an object with keys that have the same name as other variables defined elsewhere within the same block. – simmer May 19 '21 at 21:27

0 Answers0