定义适当的TypeScript接口

时间:2017-05-30 22:40:35

标签: reactjs typescript lodash

我是Typescript的新手,遇到了一个问题。我正在构建一个React Web应用程序并使用lodash。

我从api获取JSON数据。现在,让我们假设它有两个键:

{ 
  foo1 : 'something',
  bar1 : [{.. key:value data ..}, { .. key:value data ..}, ...]
}

如何为此定义界面?主要是,我有一个对象数组的事实?我尝试过这样的事情:

interface MyThing {
  foo : string;
  bar : object[];
}

然后,在reducer代码中,我有类似的东西:

let things : MyThing[] = _.forEach(apiData.things, (thingData) => ({
        foo : thingData.stringItem,
        bar : thingData.arrayOfObjects
    }))

我最终得到这样的错误:

error TS2322: Type 'object' is not assignable to type 'MyThing[]'.
  Property 'find' is missing in type '{}'.

修改 在提出建议之后,我犯了一个错误并且意味着使用_.map,而不是_.forEach。这是我得到的错误。

ERROR in ./source/reducers/gamesReducer.ts
(37,40): error TS2345: Argument of type 'object' is not assignable to parameter of type 'List<{}> | Dictionary<{}> | NumericDictionary<{}>'.
  Type 'object' is not assignable to type 'NumericDictionary<{}>'.
    Index signature is missing in type '{}'.

0 个答案:

没有答案
相关问题