Skip to content

empty return statement should be a compiler error when return type is specified #5916

Closed
@tejacques

Description

@tejacques

Currently this function compiles just fine

function foo(x): string {
    return;
}

I understand that it's happening because undefined is a valid result for a variable of type string, and this sort of related back to #185, but a midway point could be to simply require the return statement to not be empty.

Similarly, this code fails to compile:

function foo(x): string {
}

But this one compiles:

function foo(x): string {
    if(false) {
        return;
    }
}

I think the expected behavior is that every branch should require an explicit return statement.

A side benefit of this is that you can get exhausting matching completeness basically for free:

function foo(x: number | string | boolean): string {
    if(typeof x === 'number') {
        return x.toString();
    } else if (typeof x === 'string') {
        return x;
    }
}

Currently the above compiles, but if TypeScript required an explicit return in every branch for non void return functions, there would be a compiler error because there are remaining types in the union. However this would compile:

function foo(x: number | string | boolean): string {
    if(typeof x === 'number') {
        return x.toString();
    } else if (typeof x === 'string') {
        return x;
    } else if (typeof x === 'boolean') {
        return ''+x;
    }
}

This is pretty nice! There is one edge case still -- because of the implicit void included in x, calling foo(null) or foo(undefined) will return undefined. I don't know what to do about this because it relates pretty heavily to #185. I think for now it can be ignored, and whatever resolution that (hopefully) happens there will take care of it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issueGood First IssueWell scoped, documented and has the green lightHelp WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions