3 ms·
a simple solution would be > if(entry && entry.constructor === Object){}
by otrahuevada 5y ago
a simple solution would be
> if(entry && entry.constructor === Object){}
- jwalton 5y agoThis 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.
- otrahuevada 5y agoI'm having some trouble finding your proposal in the thread... how would you do it?
- jwalton 5y ago:) 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.