【问题标题】:How to define a structure in TypeScript?如何在 TypeScript 中定义结构?
【发布时间】:2023-03-14 15:06:02
【问题描述】:

我有以下 Json 身体结构。我想将其用作 Angular 8 中 POST 调用的原始主体,来自表单的输入数据,我想使其成为 JSON 结构或 Type Script 中的某些类结构,但不知道如何实现:

{
    "valueMap": {
        "A1": {
            "price": 100,
            "remaining": 200
        },
        "A2": {
            "price": 100,
            "remaining": 200
        }
    }
}

我在 Java 中做了同样的事情:

class Request {
  Map<String, Amount> valueMap = new HashMap<>();
}

class Amount {
  double price;
  double remaining;
}

【问题讨论】:

    标签: java json angular typescript


    【解决方案1】:

    Typescript 中的语法非常接近用 Java 编写的语法。以下是您将使用的接口示例:

    interface Values {
      [K: string]: Amount
    }
    
    
    interface Amount {
      price: number
      remaining: number
    }
    
    const response: Values = {
      "Key1": {
        price: 1,
        remaining: 2,
      },
      "Key2": {
        price: 1,
        remaining: 2,
      }  
    }
    
    
    

    实现这项工作的技巧是[K: string] 语法,它将索引的类型强制为字符串。

    要记住的一个警告是,索引可能只是 numberstring

    【讨论】:

      【解决方案2】:

      您可以在组件内简单地创建一个对象,并在进行 API 调用时直接使用它

      export class AppComponent  {
        valueMap = {};
      
        constructor(http: HttpClient) {
          this.valueMap['A1'] = {price: 10, remaining: 20};
          this.valueMap['A2'] = {price: 10, remaining: 20};
      
      
          http.post('http://example.com', this.valueMap)
                  .subscribe(() => {
      
          });
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-10
        • 2013-11-09
        • 2011-05-09
        • 2021-03-05
        • 1970-01-01
        • 2012-07-27
        • 1970-01-01
        相关资源
        最近更新 更多