2015-09-07 125 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)定義了屬性的形狀,所以我需要確保我使用的屬性與該屬性匹配。 –