When working with TypeScript sometimes we may come across the error message Function lacks ending return statement and return type does not include ‘undefined’. The reason for the error message is, TypeScript is thinking that we are not returning a value of the mentioned data type from the function in all scenarios.

One of the commonly occurred scenario can be like this

let myPromise = Promise.resolve('Resolved Data');

async function myFunction(): Promise<string> {
    try {
        let resolvedValue = await myPromise;
        return resolvedValue;
    } catch (error) {
        console.log(error);
    }
}

In this example, the reason is straight forward. That is, if the promise gets rejected, the flow goes into the catch block and we are not returning anything from here. So the returned value will be undefined, whereas the returned value mentioned by us is Promise<string>.

To solve this problem, we can either return some default value from the catch block or add undefined return type too to the function declaration.

example:

let myPromise = Promise.resolve('Resolved Data');

async function myFunction(): Promise<string | undefined> {
    try {
        let resolvedValue = await myPromise;
        return resolvedValue;
    } catch (error) {
        console.log(error);
    }
}

Sometimes, even when we handle all possible scenarios, TypeScript may not be able to figure out the code and show the error message.

example:

function myFunction(a: string): string {
    if (typeof a == 'string') {
        return 'howtoJS';
    } else if (typeof a != 'string') {
        return 'howtoJS.io';
    }
}

In the above function, even though we are returning a value in all possible scenarios, TypeScript still throws the error message Function lacks ending return statement and return type does not include ‘undefined’. Here, TypeScript simply checks for the final else block. If that is not present, then it throws the error message. To solve these problems, we can add a final else block.

example:

function myFunction(a: string): string {
    if (typeof a == 'string') {
        return 'howtoJS';
    } else if (typeof a != 'string') {
        return 'howtoJS.io';
    } else {
        return ''
    }
}