与Typescript反应:带有箭头功能的array.map()的类型

时间:2017-12-01 14:33:53

标签: reactjs typescript

我是js / ts的新手,但在C#方面经验丰富。现在我正在学习React并想要使用打字稿。我尝试在此演示项目中添加类型:https://github.com/bradtraversy/projectmanager/tree/master/src

export interface IProjects {  
  projects: IProjectItem[];
}

export interface IProjectItem {  
  title: string;
  category: string;  
}

class Projects extends React.Component<IProjects,object> {    

  constructor(props: IProjects) {
    super(props);
  }
  render() {    
    let projectItems = this.props.projects.map( project  => {
      return (            
        <ProjectItem project={project} /> //Error: the type "{ project: IProjectItem; }" is not assignable to "Readonly<IProjectItem>"
      );  
    });
    ...
}

class ProjectItem extends React.Component<IProjectItem,object> {    
 ...
}

我的想法是&#34;项目&#34;箭头函数中的类型为&#34; IProjectItem&#34;并且这是组件&#34; ProjectItem&#34;的正确类型。 我似乎对使用过的类型做错了。 我只在上面提到的例子中添加了类型作为来自https://www.youtube.com/watch?v=A71aqufiNtQ的视频(@~21:06) 使用给定示例的正确类型是什么?

1 个答案:

答案 0 :(得分:1)

您当前的ProjectItem类不接受count: 22 size: 7 in-pack: 148572 packs: 6 size-pack: 2913951 prune-packable: 0 garbage: 1 size-garbage: 1866072 作为其道具  对象,但它的道具是由IprojetItem接口定义的(即它接受projecttitle作为道具)。

而不是

category

你应该写

class ProjectItem extends React.Component<IProjectItem,object> {    
     ...
}
相关问题