2016-06-30 19 views
10

Ho il seguente oggetto JSON nella mia app Angular 2 e vorrei sapere qual è il giusto cosa dichiararlo in dattiloscritto.Modo corretto per dichiarare l'oggetto JSON in Typescript

data = [ 
    { 
    'id':1, 
    'title':'something' 
    'node': [ 
       { 
       'id':1, 
       'title':'something' 
       'node': [] 
       } 
      ] 
    }, 
    { 
    'id':2, 
    'title':'something' 
    'node': [ 
       { 
       'id':1, 
       'title':'something' 
       'node': [] 
       } 
      ] 
    } 
] 
+0

Cosa intende con modo corretto? Come importare il file TS int? –

+0

si desidera dichiarare un componente ricorsivo? – toskv

+0

Sarebbe meglio per me dire che questo è un oggetto Javascript. –

risposta

12

Ecco un'implementazione semplice e ingenuo di quello che stai chiedendo:

interface IDataNode { 
    id: number; 
    title: string; 
    node: Array<IDataNode>; 
} 

Se si desidera creare un'istanza detti nodi da codice:

class DataNode implements IDataNode { 
    id: number; 
    title: string; 
    node: Array<IDataNode>; 

    constructor(id: number, title: string, node?: Array<IDataNode>) { 
     this.id = id; 
     this.title = title; 
     this.node = node || []; 
    } 

    addNode(node: IDataNode): void { 
     this.node.push(node); 
    } 
} 

Usando questo per codificare la struttura:

let data: Array<IDataNode> = [ 
    new DataNode(1, 'something', [ 
     new DataNode(2, 'something inner'), 
     new DataNode(3, 'something more') 
    ]), 
    new DataNode(4, 'sibling 1'), 
    new DataNode(5, 'sibling 2', [ 
     new DataNode(6, 'child'), 
     new DataNode(7, 'another child', [ 
      new DataNode(8, 'even deeper nested') 
     ]) 
    ]) 
]; 
+1

si potrebbe desiderare di rendere la proprietà del nodo nell'interfaccia anche una matrice. :) – toskv

+0

Ah, sì - grazie;) – rinukkusu

+1

Ciao @rinukkusu se i dati provengono da json, non hai nemmeno bisogno di dichiarare una classe, puoi analizzare il json e definire un contratto con l'interfaccia, questo è il bello del dattiloscritto . – Alcruz