Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't throw for non-objects #17

Open
Jamesernator opened this issue Jun 27, 2023 · 1 comment
Open

Don't throw for non-objects #17

Jamesernator opened this issue Jun 27, 2023 · 1 comment

Comments

@Jamesernator
Copy link

Jamesernator commented Jun 27, 2023

So a footgun I recently discovered with #field in v is that as it turns out if v is not an object, then #field in v throws an error. While this is consistent with "str" in v, it makes writing a class check even less ergonomic:

function isObject(v) {
    return v !== null && (typeof v === "object" || typeof v === "function");
}

class Point2D {
    static isPoint2D(v) {
        return isObject(v) && #x in v;
    }
    
    #x;
    #y;
    
    // ...
}

It's rather easy to forget to include isObject(v) everytime one writes an SomeClass.isSomeClass method. (Further compounded by the fact one needs to implement isObject in every codebase that does such a check).

This is a great opportunity for class.hasInstance to avoid this issue if it doesn't throw for non-objects:

class Point2D {
    static isPoint2D(v) {
        return class.hasInstance(v);
    }
    
    #x;
    #y;
    
    // ...
}

Point2D.isPoint2D(new Point2D(3, 4)); // true
Point2D.isPoint2D({}); // false
// Doesn't throw, unlike #field in v
Point2D.isPoint2D(3); // false
@ljharb
Copy link
Member

ljharb commented Jun 27, 2023

v && #x in v seems a bit simpler - it won't throw on non-nullish primitives, so you don't actually need the typeof check - but you're right you need some kind of check.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants