1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00

Add Add Types To An Object Destructuring as a typescript til

This commit is contained in:
jbranchaud
2021-02-16 16:47:30 -06:00
parent 8c90548ad9
commit 98cccf82ac
2 changed files with 30 additions and 1 deletions

View File

@@ -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/)