Skip to content

Array.prototype.filter doesn't require callback to return #19456

Open
@fourlastor

Description

@fourlastor

I dig a bit and found out in #5850 and subsequently in #7779 the signature of filter has been changed not to return a boolean, so that people could return a truthy value in the implementation of the filter.

While I undertand the convenience in terms of ease of use, this as far as I observed puts developers at risk of simple bugs like the following:

const even = [1,2,3].filter(x => {
    x % 2 == 0
})

Notice the missing return statement means the function returns undefined, which translates to false, which filters all the items out. This applies also in the case of noImplicitReturns set to true, since the function return type is any, thus it could be a void function for what the compiler knows.

I believe TypeScript's job should be to put this kind of cases in check actually, so that things like truthy values (which sometimes aren't as obvious as we might think and introduce bugs we don't really understand) can be better taken care of.

One solution to make both parties happy would be to optionally support truthy values (maybe an extra compiler flag? Another truthy type to allow for more relaxed checking?) and reintroduce the original signature of filter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureDomain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions