Jonca33
Jonca33

Reputation: 3493

Types for Array Destructuring

I'm mapping through an array and using destructuring.

const newArr = arr.map(({name, age}) => `${name} ${age}`)

The above errors as: Binding element 'name' implicitly has an 'any' type

Error goes away by adding:

const newArr = arr.map(({name, age}: { name: string; age: number }) => `${name} ${age}`)

The question is: Could I go about this with a more terse syntax and/or apply the needed types via an interface?


UPDATE: As a combination from the comments below and the suggestions by @grumbler_chester and @TimWickstrom

This was the more terse way I found to shorten my syntax:

Solution:

// User.tsx
interface User {
  name: string 
  age: number
}

const newArr = arr.map(({name, age}: User) => `${name} ${age}`)

Upvotes: 3

Views: 461

Answers (2)

GreenTeaCake
GreenTeaCake

Reputation: 858

You can add type annotation to your arr variable and TS will infer type of destructed fields.

Please see example in playground (note noImplicitAny is true in options, error for arr0 mapping and no error for arr1 mapping)

And please check Type Inference for theory behind example.

Upvotes: 1

Tim Wickstrom
Tim Wickstrom

Reputation: 5701

If you would like to maintain strict type checking you could define your models.

File Architecture example.

/src
  /models
    Person.js

Person.js

export default {
  name: string,
  age: number
}

In your file

Import Person from './models/Person.js' // Path to Person.js

const newArr = arr.map(({name, age}:Person) => `${name} ${age}`)

Alternatively, if you do not require strict type checking and would like to suppress the warning this should work:

In your tsconfig.json (https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) you can add the following:

from

"noImplicitAny": false,

to

"noImplicitAny": true,

Upvotes: 2

Related Questions