Skip to content

Why does isNumber include instance check? #1652

@el-pendeloco

Description

@el-pendeloco

As I skimmed through the source code, I noticed that isNumber checks both the value of the typeof operator and instanceof Number. isString, however, only checks using the typeof operator. What is the rationale here?

It is my opinion that isNumber should not include an instanceof check. I think the natural inclination is to think of it as the primitive type. Also, they aren't exactly the same type. For example, number can be assigned to Number, but Number cannot be assigned to number.
At the very least, I believe the return type should read value is number | Number.

I'm not really sure why somebody would want to check for the wrapped typed anyway, but in this case I think another utility would be the solution:

const primitive = 42;
const wrapped = new Number(primitive);

// isNumber checks for primitive.
assert(isNumber(primitive));
assert(!isNumber(wrapped));
// isNumberObject uses instance check.
assert(!isNumberObject(primitive));
assert(isNumberObject(wrapped));

In any case, I think all primitive type guards should follow the same rationale. If isNumber uses an instanceof check, then isString should too, and so on, and their return types should signify that. I personally prefer just the primitive checks. Whaddayathink?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions