Tricks I wish I knew when I learned TypeScript
31–40 of 276 posts
Re: Tricks I wish I knew when I learned TypeScript
#32Note: don't use typeof x === 'object' to check whether something is a valid object, because it will return true for arrays as well. Arrays are objects, so this is expected behaviour.
How about any => Object.prototype.toString.call(any).slice(8, -1)
Re: Tricks I wish I knew when I learned TypeScript
#33Re: Tricks I wish I knew when I learned TypeScript
#34Nice article, I like it. I can recommend "Programming TypeScript" by Boris Cherny (O'Reilly, 2019) and "Effective TypeScript" by Dan Vanderkam (O'Reilly, 2019), if you want to learn more like this.
Re: Tricks I wish I knew when I learned TypeScript
#35The third example describes something useful in record types, but goes about it in what seems an odd way, and ends up suboptimal as a result. I'd instead use an object type like this: type Human = { name: string; age: number; } which also enforces value types in the compiler, rather than requiring runtime guards.
Which is exactly what was used in the code exemplifying something else in the second example - so that confused me (never having written any TS) too.
Re: Tricks I wish I knew when I learned TypeScript
#36Earlier quoted context omitted.
How about any => Object.prototype.toString.call(any).slice(8, -1)
I really like this package, because it not only uses the method you mentioned for checking types, but is written in TS, so you get the type checking feedback. https://github.com/sindresorhus/is
Re: Tricks I wish I knew when I learned TypeScript
#37Here's another. Instead of returning Sometype|undefined from a function which may or may not have a value to return (such as searchCustomer), return Sometype|null. That forces the function to return a value that's explicitly intended rather than defaulting from a missed out if-else codepath. This is useful since JS is often imperative style code.
Re: Tricks I wish I knew when I learned TypeScript
#38Re: Tricks I wish I knew when I learned TypeScript
#39Is there ever a reason to use interface over type? From what I’ve seen it looks like they can both do the same thing but with slight differences in syntax
Re: Tricks I wish I knew when I learned TypeScript
#40Note: don't use typeof x === 'object' to check whether something is a valid object, because it will return true for arrays as well. Arrays are objects, so this is expected behaviour.
Note: please post a better solution.
> if(entry && entry.constructor === Object){}