Re:Tricks I wish I knew when I learned TypeScript
by jwalton on Tuesday October 12, 2021 @08:07AM
(#28838719)
This isn't a great solution:
`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:
Again, entry is a valid Human here.
[ Parent
| on HN ]
Re:Tricks I wish I knew when I learned TypeScript
by otrahuevada on Tuesday October 12, 2021 @08:13AM
(#28838760)
I'm having some trouble finding your proposal in the thread... how would you do it?
Re:Tricks I wish I knew when I learned TypeScript
by jwalton on Tuesday October 12, 2021 @10:37AM
(#28840223)
:) 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.