打字稿类型'数字'不可分配│键入'字符串' [英] Typescript Type 'number' is not assignable │ to type 'string'

查看:214
本文介绍了打字稿类型'数字'不可分配│键入'字符串'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为Angular 4应用制定货币格式指令.在解析后,除去数字和小数点以外的所有内容,最后得到一个字符串化的浮点数,但是我需要它以浮点数形式返回,以便我可以对其进行数学运算.

I am currently knee deep in making a currency formatter directive for an Angular 4 app. on the parse strip out everything other than the numbers and the decimal and end up with a stringified float, but I need it to return as a float so I can do math with it.

parse(value: string, fractionSize: number = 2): number {
  let val = value.replace(/([^0-9.])+/ig, '');
  let [ integer, fraction = "" ] = (val || "").split(this.DECIMAL_SEPARATOR);
  integer = integer.replace(new RegExp(this.THOUSANDS_SEPARATOR, "g"), "");
  fraction = parseInt(fraction, 10) > 0 && fractionSize > 0
    ? this.DECIMAL_SEPARATOR + (fraction + PADDING).substring(0, fractionSize)
    : "";
  let result = `${integer}${fraction}`;
  // at this point result = "100.55";
  result = parseFloat(result); // this refuses to compile saying "Type 'number' is not assignable │ to type 'string'"
  return result;
}

推荐答案

两行:

let result = `${integer}${fraction}`;
result = parseFloat(result);

是问题所在.当未明确声明变量时,Typescript可以很好地推断出变量的类型.在这种情况下,由于您将字符串分配给 result ,因此typescript推断其类型为字符串.要解决此问题,您有两个选择.首先,显式声明该变量的类型,以便它允许包含字符串和数字:

are the problem. Typescript is pretty good about infering the type of a variable when it's not explicitly declared. In this case, because you assign a string to the result, typescript infers it's type as a string. To fix this, you have two options. First, explicitly declare the type of that variable so that it allows both strings and numbers:

let result: string|number = `${integer}${fraction}`;
result = parseFloat(result); // now should be ok.

或者您可以将解析后的数字分配给新变量,而不是重新使用 result 变量:

Or you can assign the parsed number to a new variable, instead of reusing the result variable:

let result = `${integer}${fraction}`;
let numberResult = parseFloat(result); // now should be ok.

这篇关于打字稿类型'数字'不可分配│键入'字符串'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆