2017-05-21 52 views
0

我試圖定義一個數組類型基本上是這樣的:如何在數組的typecript中定義數據類型?

[ 
    { 
    name: string, 
    comment: string 
    }, 
    { 
    name: string, 
    comment: string 
    } 
] 

,但它需要不管有多少評論有數組中工作。

我發現了一套長像這個傢伙How to define array type in typescript?

一些例子,但我不能讓它爲我做什麼工作,這裏是上下文:

class Post{ 
    person: string; 
    bird: string; 
    content: string; 
    image: string; 
    comments: Array<MyType>; 
    score: number; 
    grade: number; 
    constructor(p: string, b: string, c: string, i: string = '', cm: Array<MyType> = []) { 
    this.person = p 
    this.bird = b 
    this.content = c 
    this.image = i 
    this.comments = cm 
    this.score = 0 
    this.grade = this.score + this.cm.length 
    } 
} 

我應該如何定義類型MyType?

回答

0

我總是喜歡接口OVRE類

interface Post{ 
    person: string; 
    bird: string; 
    content: string; 
    image: string; 
    comments: Array<Comment>; 
    score: number; 
    grade: number; 
} 
interface Comment{ 
    name : string; 
    comment:string; 
} 
+0

我不會轉換'POST'作爲接口的構造從OP'POST'類有一些邏輯在裏面。儘管'Comment'應該可以用作界面。 – Saravana

+0

如果您使用模型(自定義數據類型),您可以使用該界面。如果實例保持不變,編寫類和創建實例將會遇到麻煩。 – Aravind

+0

構造函數是從OP裏面的邏輯意味着'Post'不僅僅是提供結構(接口應該是首選的),而且也是爲了創建一個你無法使用接口的Post實例。 – Saravana

0
class Post{ 
    person: string; 
    bird: string; 
    content: string; 
    image: string; 
    comments: Array<{name:string, comment:string}>; 
    score: number; 
    grade: number; 
    constructor(p: string, b: string, c: string, i: string = '', cm: Array<{name:string, comment:string}> = []) { 
    this.person = p 
    this.bird = b 
    this.content = c 
    this.image = i 
    this.comments = cm 
    this.score = 0 
    this.grade = this.score + this.cm.length 
    } 
} 
+0

好吧,所以你只定義了什麼類型的將在aray中數組的整個結構? –

+0

是的,這就是你如何模仿javascript中的類型安全檢查,你只需要告訴它你的列表包含的對象的「形狀」 – Dummy