简体   繁体   中英

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. This means that, potentially, that the function could fail all those conditional checks, and no return statement would be executed. This would result in the function returning undefined which is the the return value of a function that never explicitly returns a value. 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.

However, the return type of the function is typed as string , which means that undefined is not an allowed return value. 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.

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 and just add a return (with no value) to the end. This tells typescript that the function may return undefined and that the caller of this function needs to handle that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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