Skip to content

The implements operator should work on instances too #69

@Jamesernator

Description

@Jamesernator

From the updated explainer, I just noticed that implements is used to compare a constructor with a protocol. I don't understand why this is operating on constructors and not on instances, and what the use case for this behavior is.

Like if we had for example an Iterable protocol, it seems far more useful to be able to check whether individual objects implement such a protocol e.g.:

protocol Iterable { /* ... */ }

protocol ArrayLike { /* ... */ }

function toArray(obj: Iterable | ArrayLike) {
    if (obj implements Iterable) {
        // collect from iterator
    } else if (obj implements ArrayLike) {
        // loop over indices
    } else {
        throw new TypeError(`can't convert to array`);
    }
}

While we can solve this for at least classes by using obj.constructor instead, there is no guarantee that an arbitrary object even has a .constructor property or even a non-null prototype, but it still might otherwise have all protocol members.

It seems unfortunate to tie protocols specifically to classes, as people might well want anonymous (i.e. ordinary) objects that would otherwise have all protocol members.

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs specificsConsensus on the idea but it needs to be fleshed out with more concrete details, an algorithm, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions