【问题标题】:How to solve the problem of 'implicity has an "any" type' while mapping over an array?映射数组时如何解决“隐式具有“任何”类型的问题?
【发布时间】:2021-08-25 14:13:47
【问题描述】:

我正在尝试像这样映射数组:

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

但是当我将鼠标悬停在“项目”上时,它隐含地具有“任何”类型。我用打字稿知道了,我应该为这个函数定义参数,所以我这样尝试:

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

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

一个项目基本上由字符串和一些返回为空的项目组成:

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

我得到了所有这些错误

    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)

【问题讨论】:

  • item.payload 是一个字符串,而不是一个对象,所以这个界面一开始似乎不太正确。这里的错误也与您显示的代码不一致;你确定你正在使用你认为的代码吗?

标签: typescript api express


【解决方案1】:

将要映射的参数括在括号中

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-04
    • 2021-12-13
    • 2018-05-30
    • 2021-06-09
    • 2012-06-21
    • 2014-08-13
    • 2014-01-20
    • 2021-07-20
    相关资源
    最近更新 更多