最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Passing javascript object as an argument to a function - typescript equivalent - Stack Overflow

programmeradmin0浏览0评论

I'm trying to better understand the code in this example:

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

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

Share Improve this question asked Jun 17, 2019 at 14:16 Chris4DChris4D 1873 gold badges5 silver badges12 bronze badges 2
  • You may be confused about the destructing assignment occurring here. – Bash 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 } } }) – Caleb Liu Commented Apr 17, 2023 at 19:42
Add a ment  | 

2 Answers 2

Reset to default 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>
}

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).

发布评论

评论列表(0)

  1. 暂无评论