简体   繁体   中英

How to create object based on interface TypeScript?

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
      ]
    }
  }

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;

Try following code snippet.

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

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

You can use a regular object literal:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM