打字稿类型“编号”不可分配?输入“字符串”

Bir*_*Dad 4 types node.js angularjs typescript

我目前正在为 Angular 4 应用程序制定货币格式化程序指令。在解析中去掉数字和小数以外的所有内容,并以字符串化的浮点数结束,但我需要它作为浮点数返回,以便我可以用它进行数学运算。

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;
}
Run Code Online (Sandbox Code Playgroud)

CRi*_*ice 8

两行:

let result = `${integer}${fraction}`;
result = parseFloat(result);
Run Code Online (Sandbox Code Playgroud)

是问题所在。Typescript 在推断未显式声明的变量类型方面非常出色。在这种情况下,因为您为 分配了一个字符串,所以resulttypescript 会将其类型推断为字符串。要解决此问题,您有两个选择。首先,显式声明该变量的类型,以便它允许字符串和数字:

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

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

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