Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to declare JSON object in Typescript

Tags:

I have the following JSON object in my Angular 2 app and would like to know what is the proper what to declare it in typescript.

data = [
  {
    'id':1,
    'title':'something'
    'node': [
              {
              'id':1,
              'title':'something'
              'node': []
              }
            ]
  },
  {
    'id':2,
    'title':'something'
    'node': [
              {
              'id':1,
              'title':'something'
              'node': []
              }
            ]
  }
]
like image 937
Per Larsen Avatar asked Jun 30 '16 12:06

Per Larsen


People also ask

How would you define a JSON object in TypeScript?

We can create a JSON object in TYPESCRIPT dynamically. There are two types of objects in TypeScript. A Plain Object that we achieve with json. parse() which results in the plain object, and the TypeScript Class, which returns the Class Object.

How do I parse a JSON to a TypeScript object?

Use the JSON. parse() method to parse a JSON string in TypeScript, e.g. const result: Person = JSON. parse(jsonStr) . The method parses a JSON string and returns the corresponding value.

How do you initialize an empty JSON object in TypeScript?

Use type assertions to initialize a typed variable to an empty object, e.g. const a1 = {} as Animal; . You can then set the properties on the object using dot or bracket notation. All of the properties you set on the object need to conform to the type. Copied!


1 Answers

Here is an easy and naive implementation of what you're asking for:

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

If you want to instantiate said nodes from code:

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);
    }
}

Using this to hardcode your structure:

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')
        ])
    ])
];
like image 155
rinukkusu Avatar answered Sep 19 '22 10:09

rinukkusu