繁体   English   中英

与Typescript反应:类型缺少属性映射

[英]React with Typescript: property map is missing for type

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

到目前为止的代码:

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

export interface IProjects {  
  projects : {
    [index: number]: IProjectItem;  
  };
}


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

  constructor(props: IProjects) {
    super(props);

  this.state = {
    projects: [
    {
      title: 'Business Website',
      category: 'Web Design'
    },
    ....
  }

  render() {
    return (      
      <div className="App">
        MyApp
        <Projects projects={ this.state.projects }/>
      </div>
    );
  }
}

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

  render() {    

    if (this.props.projects)
    {
      this.props.projects.map( project => { //ERROR Property map not found for type [index:number]
        console.log(project);
      });
    }
    console.log(this.props);

    return (      
      <div className="projects">
        All Projects
      </div>
    );
  }
}

显然没有找到.map()函数。 我认为我必须更改使用的接口/类型,但是正确的接口/类型是什么?

您正在使用this.props.projects.map ;

映射用于数组[]

但是您的变量projects是JSON对象;

projects : {
    [index: number]: IProjectItem;  
  };

更改其类型。 也许

project: any[]// you will have a generic array object

要么

project: IProjectItem[] // you will have an array containing items of "IProjectItem"

正如您所怀疑的那样,问题出在您的类型定义上,尤其是这个:

export interface IProjects {  
  projects : {
    [index: number]: IProjectItem;  
  };
}

这就是说,“实现IProjects的对象将包含projects ,这是可以用数字索引的对象”。 注意,可以用数字索引的对象与数组不是同一对象,并且不会具有任何数组原型方法,例如map

另一方面,这会将其定义为数组:

export interface IProjects {  
  projects: IProjectItem[];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM