2015-09-07 128 views
4

我试图通过React Tutorial,但发生了一个我不明白的错误。React + Typescript:属性*缺少类型*

错误消息是:

comment.tsx(30,5): error TS2324: Property 'data' is missing in type 'MyProps'. 
comment.tsx(31,5): error TS2324: Property 'data' is missing in type 'MyProps'. 
main.tsx(20,17): error TS2324: Property 'author' is missing in type 'MyProps'. 
main.tsx(27,18): error TS2324: Property 'author' is missing in type 'MyProps'. 

这里是main.tsx

import * as React from 'react'; 
import 'jquery'; 
import { CommentList, CommentForm, MyProps } from './comment'; 

var data = [ 
    {author: "Pete Hunt", text: "This is one comment"}, 
    {author: "Jordan Walke", text: "This is *another* comment"} 
]; 

class CommentBox extends React.Component<MyProps, {}> { 
    render() { 
     return <div className="commentBox"> 
       <h1>Comments</h1> 
       <CommentList data={this.props.data} /> 
       <CommentForm /> 
       </div>; 
    } 
} 

$(() => { 
    React.render(<CommentBox data={data} />, document.getElementById('content')); 
}); 

而且comment.tsx

import * as React from 'react'; 

export interface MyProps extends React.Props<any> { 
    author: string; 
    data: Array<any>; 
} 

export class Comment extends React.Component<MyProps, {}> { 
    render() { 
     let rawMarkup = marked(this.props.children.toString(), {sanitize: true}); 
     return <div className="comment"> 
       <h2 className="commentAuthor"> 
        {this.props.author} 
       </h2> 
       <span dangerouslySetInnerHTML={{__html: rawMarkup}} /> 
       </div>; 
    } 
} 

export class CommentList extends React.Component<MyProps, {}> { 
    render() { 
     return <div className="commentList"> 
       <Comment author="Pete Hunt">Some comment</Comment> 
       <Comment author="Jordan Walke">Another *comment*</Comment> 
       </div>; 
    } 
} 

export class CommentForm extends React.Component<{}, {}> { 
    render() { 
     return <div className="commentForm"> 
       A CommentForm 
       </div>; 
    } 
} 

我记得读取接口仅仅是进行类型检查和不存在于传输的代码中。但是,我仍然不完全明白为什么我会收到这些错误。

此外,我使用DefinitelyTyped的类型定义。

回答

4

comment.tsx(30,5):错误TS2324:'MyProps'类型中缺少属性'data'。 comment.tsx(31,5):错误TS2324:'MyProps'类型中缺少属性'data'。 main.tsx(20,17):错误TS2324:'MyProps'类型中缺少属性'author'。 main.tsx(27,18):错误TS2324:'MyProps'类型中缺少属性'author'。

你可能混淆了CommentMyPropsCommentList(不含.author)和MyProps(不含.data)。

如果您使用不同两个组件的接口更好。

+1

谢谢。创建单独的接口解决了问题。查看编译后的JS也有帮助,基本上'一些注释'成为'React.createElement(Comment,{“author”:“Pete Hunt”},“Some comment”)''。所以JavaScript中的'prop'就是'{“author”:“Pete Hunt”}'。 因此,TypeScript告诉我,我从未在'Comment'上使用'data'属性?对于TypeScript中接口如何工作,我仍然有点模糊。基本上为什么有两个“MyProps”? –

+0

两个独立的接口*两个独立的*合同*两个独立的组件 – basarat

+0

谢谢。我猜'契约'是关键词。 “React.Component ”的第一个参数(P)定义了属性的形状,所以我需要确保我使用的属性与该属性匹配。 –