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
The two definitions are not identical, the first one takes one parameter named
data
of typeMyDataType
and the second takes an object with one property nameddata
, of typeMyDataType
.The second signature makes use of destructuring which extracts
data
for use in the function body, so in both cases you have onedata
variable of typeMyDataType
available in the function scope.The only difference is the structure of the input parameter.
Both are different here based on the type of parameters:
accept parameter
data
with typeMyDataType
accept parameter object with the
data
propety asMyDataType
typeIf we suppose to enhance and add more parameters then recommended would be second one so we can destructure as much as we can:
Hope it will help you to decide.