【问题标题】:Type 'number' is not assignable to type 'string'. How to cast number to string类型“数字”不可分配给类型“字符串”。如何将数字转换为字符串
【发布时间】:2019-10-09 23:39:03
【问题描述】:

我想在 Angular 7 的打字稿文件中将数字转换为字符串。我想向后端发送两个数据,一个 ID 和一个名称。后端只接受名称。如何解决此错误?

 public saveCode(e): void {
    let name = e.target.value;
    let list = this.codeList.filter(x => x.name === name)[0];


//This one gives the error
    this.restaurant.restaurantId = list.restaurantId;


//This one works
    this.restaurant.name = list.name;

我想把 restaurantId 改成字符串。

【问题讨论】:

    标签: json angular typescript rest glassfish


    【解决方案1】:

    任何人都会简单地使用 toString() 方法

    this.restaurant.restaurantId = list.restaurantId.toString();
    

    【讨论】:

    • 啊,我反其道而行之。感谢您的帮助。
    【解决方案2】:

    您可以通过以下方式转换为字符串:

    this.restaurant.restaurantId = '' + list.restaurantId;
    

    this.restaurant.restaurantId = `${list.restaurantId}`;
    

    【讨论】:

      【解决方案3】:

      您可以使用toString()String(),如下所示。

      value.toString()
      

      或者

      String(value)
      

      或者

      "" + value
      

      【讨论】:

        【解决方案4】:

        您也可以使用String 方法将整数转换为这样的字符串

        x = 12;
        String(x);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-03
          • 2021-10-21
          • 2021-10-13
          • 2019-09-06
          相关资源
          最近更新 更多