Skip to content

Use instanceof instead of is in type guard function syntax #3437

Closed
@mihailik

Description

@mihailik

The type guard syntax introduces a new keyword is
#1007 Support user-defined type guard functions
#3262 Custom type guard function

(the latter was implemented by @tinganho and merged in master recently with 6e69a9e )

The syntax is quite elegant and clean, but can be further improved. It's generally a good rule to try and avoid introducing new keywords. Especially when a very similar one already exists in the language.

I suggest we use the existing instanceof instead. The meaning fits, and it's very familiar to a lay JS folk.

In simple words, to a person with JS background, but a limited TS one (1) leaves more to guess than (2):

function isApple(p1: any): p1 is Apple { }    // (1)   <-- man... let me remember what's the difference...

function isApple(p1: any): p1 instanceof Apple { }    // (2)   <-- hello, I know you!

I do agree that for the C# audience they both are fine. But similarly to bool/boolean swap of the early TS versions, preferring JS over C# is the right thing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptWon't FixThe severity and priority of this issue do not warrant the time or complexity needed to fix it

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions