skip to Main Content

I’m working on a TypeScript project and came across two different parameter definitions in some code. Both seem to achieve the same result, but I’m not sure if there’s any significant difference between them. Could someone please explain the difference between the following two parameter definitions?

export default function myFunc(data: MyDataType) {}

vs

export default function myFunc({ data }: { data: MyDataType }) {}

Both definitions seem to accept an object of type MyDataType as a parameter. Are there any advantages or specific use cases for using one over the other? Any insights would be appreciated. Thank you!

2

Answers


  1. The two definitions are not identical, the first one takes one parameter named data of type MyDataType and the second takes an object with one property named data, of type MyDataType.

    The second signature makes use of destructuring which extracts data for use in the function body, so in both cases you have one data variable of type MyDataType available in the function scope.

    The only difference is the structure of the input parameter.

    Login or Signup to reply.
  2. Both are different here based on the type of parameters:

    export default function myFunc(data: MyDataType) {}
    

    accept parameter data with type MyDataType

    export default function myFunc({ data }: { data: MyDataType }) {}
    

    accept parameter object with the data propety as MyDataType type

    If we suppose to enhance and add more parameters then recommended would be second one so we can destructure as much as we can:

    export default function myFunc({ data, data2, data3 }: { data: MyDataType, data1: MyDataType1, data2: MyDataType2 }) {}
    

    Hope it will help you to decide.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search