triston-notes/Cards/dev/TS to annotate or not to annotate.md
2023-10-21 18:52:54 -05:00

1.6 KiB
Raw Blame History

up:: TypeScript

Typscript (not)to annotate all types

explicit manifest type annotations can be thought of as double-entry bookkeeping in accounting: when you do everything right, it should never be needed. - some say

A good rule of thumb is:

Every public interface should be explicitly annotated, unless the type is blindingly obvious both from the name and the implementation

So, for something like

export const toString = (num) => `${num}`

Some believe its ok to leave out type annotations - even tho num would normally be typed - just example

Ive come to find out that its 100% preference.

Some believe you write cleaner code by letting typescript infer the return types. Some believe its cleaner and more readable without inferring

I personally am a huge fan of typing everything. So for me, this feels much much better:

export const toString = (num: number): string => `${num}`

I just FEEL better.

Whether its cleaner to someone else or not, or pointless for me to do. Its 100% preference and this is my preference.

Obviously when working on a team, you want to write code that appeals to the team and not just yourself.

But youll never satisfy anyone with your personal taste because everyone has a different taste.

The closer mistake to the type declaration: the easier it is to fix it. If you, after refactoring, accidentally change the return expression so that it returns a different type - the type check error will be triggered several layers deeper on the first caller whose expectations you have broken (if any).

always type all functions explicitly. - my motto