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?
[ Parent
| on HN ]
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.