【发布时间】:2021-11-12 23:48:44
【问题描述】:
我第一次尝试将 js 文件重写为 ts。我是 TS 新手,不认识所有各种语法问题。不过,它看起来也……对我来说还不错。
那么为什么会出现这个错误呢?
function processAmount(number: number, displayedInFeed: boolean): string {
// turns "2707" -> "2,707" and "306438" -> "306k"
const amtAsString: string = number.toString();
if (amtAsString.length <= 3) {
// handles values like "123" and other 3 digit nums
return amtAsString.toString();
} else if (amtAsString.length === 4) {
// converts "1234" -> "1,234"
return amtAsString[0] + "," + amtAsString.slice(1);
} else if (amtAsString.length > 4 && amtAsString.length <= 6) {
// "306903" -> "306k"
return amtAsString.slice(0, 3) + "k";
} else if (amtAsString.length > 6) {
// "65,730,395" -> "65.7m"
let mil: string = " million";
if (displayedInFeed) {
mil = "m";
}
let millionLvlString: string = amtAsString.substring(0, amtAsString.length - 6) +
"." +
amtAsString[amtAsString.length - 6] +
mil
return millionLvlString
}
}
export default processAmount;
错误:
TypeScript error in C:/Users/path/to/file/ProcessAmount.ts(12,82):
Function lacks ending return statement and return type does not include 'undefined'. TS2366
10 | * Purpose of function is to convert 10,000 => 11.3k, 101,000 => 101k, 1,000k => 1.00m, and beyond.
11 | */
> 12 | export default function processAmount(number: number, displayedInFeed: boolean): string {
| ^
13 |
14 | // turns "2707" -> "2,707" and "306438" -> "306k"
15 | // console.log(number
我的理解是,如果我按照我的方式声明函数参数后加上: string {,我应该不会有错误。
这可能与没有 tsconfig 文件有关。不过我不确定。请高手!
请注意,this did not help me understand my failure 和 this 都不是。我在 TS 有点太新了。
当我解决错误时,我正在寻找 tsc processAmount.ts 将程序编译成 js。但是,这也不起作用,它说:
error TS6053: File 'processAmount.ts' not found.
The file is in the program because:
Root file specified for compilation
怎么办?
【问题讨论】:
-
想想控制流:如果条件都不成立怎么办?
-
@DaveNewton 在技术上是不可能的。但是,TS 并没有分析
if/else链涵盖了所有可能性。 -
@DaveNewton 我也知道,但我认为这就是 OP 的绊脚石。期望所有的情况都是所有的情况。编辑:and latest still doesn't catch it
-
以上接受的答案解释了您所遇到的情况。
标签: reactjs typescript