Function declarations

Function declarations

Destructuring also works in function declarations. For simple cases this is straightforward:

type C = {a: string, b?: number}
function f({a, b}: C): void {
  // ...
}

But specifying defaults is more common for parameters, and getting defaults right with destructuring can be tricky. First of all, you need to remember to put the type before the default value.

function f({a, b} = {a: "", b: 0}): void {
  // ...
}
f(); // ok, default to {a: "", b: 0}

Then, you need to remember to give a default for optional properties on the destructured property instead of the main initializer. Remember that C was defined with b optional:

function f({a, b = 0} = {a: ""}): void {
  // ...
}
f({a: "yes"}) // ok, default b = 0
f() // ok, default to {a: ""}, which then defaults b = 0
f({}) // error, 'a' is required if you supply an argument

Use destructuring with care. As the previous example demonstrates, anything but the simplest destructuring expressions have a lot of corner cases. This is especially true with deeply nested destructuring, which gets really hard to understand even without piling on renaming, default values, and type annotations. Try to keep destructuring expressions small and simple. You can always write the assignments that destructuring would generate yourself.

doc_TypeScript
2016-10-04 19:25:13
Comments
Leave a Comment

Please login to continue.