From 98cccf82acddd38437818ce3a97cc023418b42eb Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 16 Feb 2021 16:47:30 -0600 Subject: [PATCH] Add Add Types To An Object Destructuring as a typescript til --- README.md | 3 +- .../add-types-to-an-object-destructuring.md | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 typescript/add-types-to-an-object-destructuring.md diff --git a/README.md b/README.md index 72fd6d6..f9ab2bf 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1049 TILs and counting..._ +_1050 TILs and counting..._ --- @@ -953,6 +953,7 @@ _1049 TILs and counting..._ ### TypeScript +- [Add Types To An Object Destructuring](typescript/add-types-to-an-object-destructuring.md) - [Re-Export An Imported Type](typescript/re-export-an-imported-type.md) ### Unix diff --git a/typescript/add-types-to-an-object-destructuring.md b/typescript/add-types-to-an-object-destructuring.md new file mode 100644 index 0000000..598306e --- /dev/null +++ b/typescript/add-types-to-an-object-destructuring.md @@ -0,0 +1,28 @@ +# Add Types To An Object Destructuring + +Let's say I'm building a form component that asks the user for their first name +and email address. I then want to submit these values to some server endpoint +to subscribe the user to a newsletter. + +Now, what if I want to type the destructuring of the form values? + +The standard syntax for doing this with TypeScript conflicts with the +destructured renaming ES6 feature: + +```javascript +const { firstName: string, email: string } = formValues; +``` + +This won't work. + +Rather than typing the individual values in the destructuring, you'll need to +type the destructured object itself. + +```typescript +const { + firstName, + email, +}: { firstName: string; email: string } = formValues; +``` + +[source](https://flaviocopes.com/typescript-object-destructuring/)