简体   繁体   English

将 JavaScript 函数重构为 TypeScript?

[英]Refactor JavaScript function to TypeScript?

I just started studying typescript (really just started) and I'm trying to make this function work when running this test:我刚刚开始学习打字稿(真的才刚刚开始),我正在尝试在运行此测试时使此功能正常工作:

import { convertNumberToEnglishText } from './index';

describe('Number to English converter test suite', () => {
    it('should print zero for 0', () => {
        expect(convertNumberToEnglishText(0)).toBe('zero');
    });

    it('should print zero for 0', () => {
        expect(convertNumberToEnglishText(-0)).toBe('zero');
    });

    it('should print negative one for -1', () => {
        expect(convertNumberToEnglishText(-1)).toBe('negative one');
    });

    it('should print nineteen for 19', () => {
        expect(convertNumberToEnglishText(19)).toBe('nineteen');
    });

    it('should print twenty for 20', () => {
        expect(convertNumberToEnglishText(20)).toBe('twenty');
    });

    it('should print correctly for 41', () => {
        expect(convertNumberToEnglishText(41)).toBe('forty one');
    });

    it('should print correctly for 100', () => {
        expect(convertNumberToEnglishText(100)).toBe('one hundred');
    });

    it('should print correctly for 101', () => {
        expect(convertNumberToEnglishText(101)).toBe('one hundred one');
    });

    it('should print correctly for 739', () => {
        expect(convertNumberToEnglishText(739)).toBe('seven hundred thirty nine');
    });

    it('should print correctly for 1234', () => {
        expect(convertNumberToEnglishText(1234)).toBe('one thousand two hundred thirty four');
    });

    it('should print correctly for 10000', () => {
        expect(convertNumberToEnglishText(10000)).toBe('ten thousand');
    });

    it('should print correctly for 60019', () => {
        expect(convertNumberToEnglishText(60019)).toBe('sixty thousand nineteen');
    });

    it('should print correctly for 67567', () => {
        expect(convertNumberToEnglishText(67567)).toBe('sixty seven thousand five hundred sixty seven');
    });

    it('should print correctly for 99999', () => {
        expect(convertNumberToEnglishText(99999)).toBe('ninety nine thousand nine hundred ninety nine');
    });
});

The only error I get in the function is on the first string type declaration in the first line.我在函数中遇到的唯一错误是第一行的第一个字符串类型声明。 It says "Function lacks ending return statement and return type does not include 'undefined'."它说“函数缺少结束返回语句并且返回类型不包括'未定义'。”

export function convertNumberToEnglishText(n: number): string {
    const num = [
        "zero",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
        "ten",
        "eleven",
        "twelve",
        "thirteen",
        "fourteen",
        "fifteen",
        "sixteen",
        "seventeen",
        "eighteen",
        "nineteen",
    ];
    const tens = [
        "ten",
        "twenty",
        "thirty",
        "forty",
        "fifty",
        "sixty",
        "seventy",
        "eighty",
        "ninety",
    ];
    
        if (n <= 0) return "negative " + convertNumberToEnglishText(-n);
    
        let digit: number = n % 10;
    
        if (n >= 0 && n < 20) return `${num[n]}`;
    
        if (n >= 20 && n < 100) return `${tens[Math.floor(n / 10) - 1]} ${digit != 0 ? num[digit] : ""}`;
    
        if (n >= 100 && n < 1000) {
            return `${num[Math.floor(n / 100)]} hundred ${
                n % 100 == 0 ? "" : convertNumberToEnglishText(n % 100)
            }`;
        }
    
        if (n >= 1000 && n < 10000) {
            return `${num[Math.floor(n / 1000)]} thousand ${
                n % 1000 != 0 ? convertNumberToEnglishText(n % 1000) : ""
            }`;
        }
    
        if (n >= 10000 && n < 20000) {
            return `${num[Math.floor(n / 1000)]} thousand ${
                n % 1000 != 0 ? convertNumberToEnglishText(n % 1000) : ""
            }`;
        }
    
        if (n >= 20000 && n < 100000) {
            return `${tens[Math.floor(n / 10000) - 1]} ${
                num[Math.floor(n / 10000)]
            } thousand ${n % 1000 != 0 ? convertNumberToEnglishText(n % 1000) : ""}`;
        }
}

Every single return statement in this function is nested inside a conditional branch.此函数中的每个return语句都嵌套在条件分支中。 This means that, potentially, that the function could fail all those conditional checks, and no return statement would be executed.这意味着,该函数可能无法通过所有这些条件检查,并且不会执行 return 语句。 This would result in the function returning undefined which is the the return value of a function that never explicitly returns a value.这将导致函数返回undefined ,这是从未显式返回值的函数的返回值。 This will happen with your function if you pass in a value of more than 100000 , as there is no conditional branch to handle that.如果您传入的值超过100000 ,您的函数就会发生这种情况,因为没有条件分支来处理它。

However, the return type of the function is typed as string , which means that undefined is not an allowed return value.但是,函数的返回类型是string类型,这意味着undefined不是允许的返回值。 This what the error means.这就是错误的含义。

You need to define what happens when the input is out of the bounds your function handles.您需要定义当输入超出您的函数处理范围时会发生什么。 There are a lot of ways to do that, depending on what you want to do.有很多方法可以做到这一点,这取决于您想要做什么。


You could throw an error as the last line of your function.您可以在函数的最后一行抛出错误。 This would only be hit if all other conditional clauses fail and no return statement is ever executed.只有在所有其他条件子句都失败并且从未执行过 return 语句时才会命中。

throw new Error("Only values below 100,000 are supported")

You could fallback to just printing the number as digits as the last line:您可以回退到仅将数字打印为最后一行的数字:

return n.toString()

Or you could change your return type to string | undefined或者您可以将返回类型更改为string | undefined string | undefined and just add a return (with no value) to the end. string | undefined ,只需在末尾添加一个return值(没有值)。 This tells typescript that the function may return undefined and that the caller of this function needs to handle that case.这告诉打字稿该函数可能返回undefined并且该函数的调用者需要处理这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM