3

I'm trying to better understand the code in this example: https://codesandbox.io/s/r5n96yvwnm

So there is this function (lines 9-11):

function MyCell({ value, columnProps: { rest: { someFunc } } }) {
  return <a href="#" onClick={someFunc}>{value}</a>
}

What construct is it, and is it possible to translate it easily into Typescript? I mean, I could go ahead and create a typescript interface with all needed props but I was wondering, if there is any shorter way of doing so. I have never seen a construct like this, so any links with more explanation appreciated.

Thanks

2
  • You may be confused about the destructing assignment occurring here. Commented Jun 17, 2019 at 14:23
  • if you don't want to make a separate interfact try function MyCell({ value, columnProps: { rest: { someFunc } } }:{ value: number, columnProps: { rest: { someFunc: () => void } } }) Commented Apr 17, 2023 at 19:42

2 Answers 2

3
function MyCell({ value, columnProps: { rest: { someFunc } } }) {

This part is using destructuring to pick the properties off of an object. It's the same as:

function MyCell(props) {
  const value = props.value;
  const columnProps = props.columnProps;
  const rest = columnProps.rest;
  const someFunc = rest.someFunc;

Doing this with typescript would look something like this (i'm guessing at some of the types in the interface):

interface MyCellProps {
  value: number;
  columnProps: {
    rest: {
      someFunc: () => void;
    }
  }
}

function MyCell: React.FC<MyCellProps>({ value, columnProps: { rest: { someFunc } } }) {
   return <a href="#" onClick={someFunc}>{value}</a>
}
Sign up to request clarification or add additional context in comments.

Comments

2

Sounds like the params are confusing you. MyCell is a function that takes a single parameter. That parameter is expected to be an object with properties value and columnProps. columnProps is also expected to be an object, with the property rest. rest is likewise expected to be an obj with prop someFunc.

This is called object destructuring, and in the specific case of using it in parameters, it's called unpacking (mdn).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.