4 ms·
My only issue with this is that it introduces the possibility for human error. It’s rare, but if the returned object fits more than one type (say, a superclass
by corytheboyd 6y ago
My only issue with this is that it introduces the possibility for human error. It’s rare, but if the returned object fits more than one type (say, a superclass vs concrete class instance) the incorrect one could be selected and the code still compile. Is this even a valid concern?
The only time I see manual type annotation cause problems consistently is with React.FC<Props>: (props: T). People don’t always remember to provide their props interface as the generic, and instead directly annotate the props argument of the function. This is a subtle issue that breaks the “magic” props added by React (like children), leading to people adding their own children definitions to their props interfaces d’oh
- codeflo 6y agoI personally find that manual return type annotations actually prevent some errors. A common case: I forget the return statement in one branch, and TypeScript is happy to infer something like number|undefined as the return type.
- Klathmon 6y ago>leading to people adding their own children definitions to their props interfaces IMO this is a feature not a bug. Type definitions aren't just for the compiler, they're also for the developer. Being able to see at a glance which components expect children and which don't is really valuable. Not to mention that there are situations where I want to restrict what kinds of children can be passed in (think render-props, or named slot projection patterns). In other words, just because React supports an implicit definition of what a "child" can be doesn't mean that my specific component supports all of those same possibilities.
- corytheboyd 6y agoI see your point, and agree under the condition that I trust everyone contributing to the codebase knows it. But, in reality, they don’t. I’d rather have the children type available but unused most of the time than one-off type definitions of children. Maybe for you my own projects I’ll employ your approach, because I agree from the fundamentals side of it