3

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}`)
7
  • 2
    Relevant github issue: github.com/Microsoft/TypeScript/issues/7576 Commented Jan 16, 2019 at 17:00
  • Is arr variable typified? Commented Jan 16, 2019 at 17:08
  • @grumbler_chester How so? Commented Jan 16, 2019 at 17:09
  • @Jonca33 Does it have some type annotation like: type User { name: string; age: number; } const arr: User[] = ... Commented Jan 16, 2019 at 17:11
  • @grumbler_chester I didn't add any types to arr. Suggestions? Commented Jan 16, 2019 at 17:12

2 Answers 2

2

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,
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

@Jonca33 I cannot provide you exact answer without the code but in general usual reason for such error is a collision when TS loses/cannot infer type of arr somewhere "above".
indeed, I appreciate your insight, that lead me to a solution, please see my updated question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.