How to solve the problem of 'implicity has an "any" type' while mapping over an array?

Issue

I’m trying to map over an array like this:

const formatted = results.map(item => item.payload)

but I get that ‘item’ implicity has an "any" type when I hover over it. I get that with typescript I should be defining the parameter for this function, so I tried it like this:

interface IItem {
   alert_id: null
   event_type: string
   id: string
   payload: string
   timestamp: string
}

const formatted = results.map(item: IItem => item.payload)

An item basically consists of strings and some items which are being returned as null:

{
   alert_id: null
   event_type: "test"
   id: "sd09f82-f8asf"
   payload: "{'test': 'accepted'}"
   timestamp: "2019-12-10"
}

and I get all of this errors

    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: тип Unable to compile TypeScript:
src/application.ts:31:11 - error TS6196: 'IItem' is declared but never used.

31 interface IItem {
             ~~~~~
src/application.ts:65:54 - error TS7006: Parameter 'IItem' implicitly has an 'any' type.

65     const formatted = results.map(item: IItem => item.payload)
                                                        ~~~~~
src/application.ts:65:63 - error TS2532: Object is possibly 'undefined'.

65     const formatted = results.map(item: IItem => item.payload)
                                                                 ~~~~~
src/application.ts:65:69 - error TS2339: Property 'payload' does not exist on type 'Event'.

65     const formatted = results.map(item: IItem => item.payload)
                                                                       ~~~~~~~
src/application.ts:65:52 - error TS1005: ',' expected.

65     const formatted = results.map(item: IItem => item.payload)

Solution

Enclose the arguments to map in parantheses

const formatted = results.map((item: IItem) => item.payload).

Answered By – Gaurav

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published