![](/img/trans.png)
[英]Momentjs with Typescript : “type string is not assignable to type 'Date'”
[英]Typescript Type 'number' is not assignable │ to type 'string'
我目前正在為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;
}
兩行:
let result = `${integer}${fraction}`;
result = parseFloat(result);
是問題。 當沒有明確聲明變量時,Typescript非常擅長推斷變量的類型。 在這種情況下,因為您為result
分配了一個字符串, result
typescript推斷它的類型為字符串。 要解決此問題,您有兩個選擇。 首先,顯式聲明該變量的類型,以便它允許字符串和數字:
let result: string|number = `${integer}${fraction}`;
result = parseFloat(result); // now should be ok.
或者,您可以將解析后的數字分配給新變量,而不是重新使用result
變量:
let result = `${integer}${fraction}`;
let numberResult = parseFloat(result); // now should be ok.
您不能為Typescript中的變量分配不同的類型。 如果使用string
初始化變量,則該變量必須保留為string
。
let result = `${integer}${fraction}`;
let resultAsNumber = parseFloat(result);
return resultAsNumber
這是類型系統試圖阻止您執行此操作的常見錯誤原因。
有一個明顯的錯誤,您正在嘗試為字符串變量分配一個數字,而無需再次解析為Float,只需通過解析即可返回該數字
let result = `${integer}${fraction}`;
// at this point result = "100.55";
return parseFloat(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.