How to correctly specify types when destructuring objects in TypeScript?
Hello! I've just started learning TypeScript and encountered a problem with object destructuring. Let's say I have a function that takes a user settings object, and I want to destructure it directly in the parameters:
```typescript
function createUser({name, age, email}) {
// ... code
}
```
But TypeScript complains that the parameters don't have types. I tried writing it like this:
```typescript
function createUser({name: string, age: number, email: string}) {
// ...
}
```
But that doesn't work — it interprets `string`, `number` as new variable names, not types. Then I tried another option:
```typescript
function createUser({name, age, email}: {name: string, age: number, email: string}) {
// ...
}
```
This seems to work, but it looks cumbersome.
No answers yet.
Log in to leave an answer
Blogs