danvk / effective-typescript

Effective TypeScript 2nd Edition: 83 Specific Ways to Improve Your TypeScript
https://effectivetypescript.com
Other
1.57k stars 229 forks source link

The Golden Rule of Generics #9

Open danvk opened 2 years ago

danvk commented 2 years ago

The Golden Rule of Generics

https://effectivetypescript.com/2020/08/12/generics-golden-rule/

danvk commented 2 years ago

Comment by Viacheslav Dobromyslov (viacheslavdobromyslov) on 2020-08-13 06:12:

Thank you for these examples. I want to add just one small note: els.map(el => '' + el) is not a good way to convert number to string. ESlint will mark it as an error.

danvk commented 2 years ago

Comment by danvdk on 2020-08-14 10:38:

Are you referring to the no-implicit-coercions rule? The argument against '' + x for string coercion there is entirely stylistic. Error and "not a good way" seem a bit strong for a matter of style.

danvk commented 2 years ago

Comment by Zackery Zing (zackeryzing) on 2020-08-14 02:59:

In my linting rules, I always force functions to have a return type. I think in an article like this it is useful to have return types on all functions so there is no missing information.

danvk commented 2 years ago

Comment by danvdk on 2020-08-14 07:35:

What I’d really like is to have mouseover in the code snippets on the blog to see the inferred type, just like in your editor. I know some people (and some linters) insist on annotating all return types, but I do not.

danvk commented 2 years ago

_Comment by Romain Deneau (romain_deneau) on 2020-08-18 04:22:_

Useful rule, nicely explained in this article 👍

I suggest to rename it "The Golden Rule of Generic Functions", because it's about functions, not all generic types - see basic counter example: in this generic type, type WithValue<t> = { value: T }, T appears only once.

danvk commented 2 years ago

Comment by Vincent Jaubert (vincentjaubert) on 2021-05-16 05:14:

This is indeed pure gold, thank you.

danvk commented 2 years ago

Comment by ThomasBurleson on 2021-12-07 11:32:

I really enjoyed reading this. Very important heuristics.