简体   繁体   English

如何基于接口TypeScript创建对象?

[英]How to create object based on interface TypeScript?

I have the following interface in TypeScript: 我在TypeScript中具有以下接口:

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

I need to create object based on this interface Defined : 我需要基于此接口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: 我有一个基于JSON对象,需要创建JS对象:

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

Let's start off with a valid JSON string: 让我们从一个有效的JSON字符串开始:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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