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});
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});
Share
Improve this question
edited Mar 21, 2019 at 6:10
neaumusic
asked Mar 20, 2019 at 23:38
neaumusicneaumusic
10.5k11 gold badges59 silver badges86 bronze badges
4
-
5
You cannot. Keep
props
as an argument thenconst { id } = props;
– zerkms Commented Mar 20, 2019 at 23:39 - Your code works when I try it. – Barmar Commented Mar 20, 2019 at 23:42
-
2
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 dofunction go(props, {id}=props)
– Khauri Commented Mar 20, 2019 at 23:45 - 1 @KhauriMcClain that's a dirty hack but I genuinely like it! :-) – zerkms Commented Mar 20, 2019 at 23:56
2 Answers
Reset to default 6You 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});
You can follow this approach which names a param as props and destructures that param to extract the value of Id.
The problem es 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});