What's the JavaScript syntax to cast and destructure a param?
Asked Answered
D

2

5

This seems like a stupid question. Say I have a function which accepts an object. How can I cast that object as props, but also destructure props.id to id (in the parameter declaration)?

function go ({ id }) {
  const props = arguments[0]; // how to do this with destructure?
  console.log('props', props, 'id', id);
}

go({id: 2});
Dudeen answered 20/3, 2019 at 23:38 Comment(4)
You cannot. Keep props as an argument then const { id } = props;Kirman
Your code works when I try it.Barde
Zerkms has the best answer, but if you don't care about code quality and you know the go function won't receive extra parameters, you can do function go(props, {id}=props)Baskett
@KhauriMcClain that's a dirty hack but I genuinely like it! :-)Kirman
Z
6

You can't do it - just keep props as an argument as well to make this code simpler and easier to read:

function go (props) {
  const { id } = props;
  console.log('props', props, 'id', id);
}

go({id: 2});
Zwick answered 20/3, 2019 at 23:44 Comment(0)
E
3

You can follow this approach which names a param as props and destructures that param to extract the value of Id.

The problem comes when you need to pass an additional param.

function go (props, {id} = props) {
  //const props = arguments[0]; // how to do this with destructure?
  console.log('props', props, 'id', id);
}

go({id: 2});
Eventful answered 20/3, 2019 at 23:50 Comment(1)
even worse problem would come if a caller passes the second parameter accidentallyKirman

© 2022 - 2024 — McMap. All rights reserved.