1

I have the following interface in TypeScript:

export interface Defined {
   4475355962119: number[];
   4475355962674: number[];
}

I need to create object based on this interface Defined:

let defined = new Defined();
defined['4475355962119'] = [1];
defined['4475355962674'] = [2];

But it does not work for me!

Or may be it should be something as:

 export interface Defined {
      array(number): number[];
}

I have this JSON object based that I need to create JS objects:

  "parameters": {
    "defined": {
      4475355962119: [
      9547,
      9871
      ],
      4475355962674: [
      9829
      ]
    }
  }

3 Answers 3

3

Let's start off with a valid JSON string:

const data = `{
    "parameters": {
    "defined": {
      "4475355962119": [9547,9871],
      "4475355962674": [9829]
    }
  }
}`;

Interface

If we want to represent this as an interface, the thought process is to keep all the keys, and replace any values with their respective types, like this:

interface Data {
    parameters: {
        defined: {
            [index: number]: number[];
        }
    }
}

We can then deserialize the data into that type:

const result = <Data>JSON.parse(data);

And obtain just the "defined" bit:

const defined = result.parameters.defined;

Complete Example

Here is a complete example:

const data = `{
    "parameters": {
    "defined": {
      "4475355962119": [9547,9871],
      "4475355962674": [9829]
    }
  }
}`;

interface Data {
    parameters: {
        defined: {
            [index: number]: number[];
        }
    }
}

const result = <Data>JSON.parse(data);

alert(result.parameters.defined['4475355962674'][0]); // 9829

Creating Data

If you aren't deserializing the data, you can create it yourself. The type annotation will help you create a correct object.

const example: Data = {
    parameters: {
        defined: {
            '4475355962674': [0, 2, 3]
        }
    }
};

example.parameters.defined['4475355962674'][3] = 4;
Sign up to request clarification or add additional context in comments.

1 Comment

How to fill result.parameters.defined? I mean to create new key and add values as value (array)
0

Try following code snippet.

export interface Defined {
   4475355962119: number[];
   4475355962674: number[];
}

let defined = {} as  Defined;
defined['4475355962119'] = [1];
defined['4475355962674'] = [2];

1 Comment

But when defined can contains some others key (number) : []?
0

You can use a regular object literal:

let defined = {
    4475355962119 : [1],
    4475355962674 : [2]
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.