Hacker News new | ask | show | jobs
by jwalton 1709 days ago
This isn't a great solution:

    entry = Object.create(null);
    entry.name = "Jason";
    entry.age = 42;
    entry.constructor === Object // false - constructor is undefined.
`entry` is a valid Human here, but fails your check. Actually, just creating a new class that implements the Human interface will cause a similar problem, since the constructor will be the class instead of Object. You don't even really want to exclude arrays here:

    entry = []
    entry['name'] = "Jason";
    entry['age'] = 42;
Again, entry is a valid Human here.
1 comments

I'm having some trouble finding your proposal in the thread... how would you do it?
:) Fair enough:

    function isHuman(obj: unknown): obj is Human {
      return !!obj && 
        typeof obj === 'object' &&
        typeof (obj as any).name === 'string' &&
        typeof (obj as any).age === 'number';
    }
This checks the shape of the object, and returns true if it's a `Human`. This will work for array or objects or classes or anything.