Home > Software design >  When I need to explicitly define the type of a const?
When I need to explicitly define the type of a const?

Time:01-05

Basically, I want to know if it's right or wrong to explicitly define the type of consts, for example:

Here I have a const which it's type shows when I simply put the mouse over, typescript got the type automatically:

enter image description here

but, can I explicit show the type like this?

const tasksRef: CollectionReference<DocumentData> = collection(db, "tasks");

My question is, is this wrong, right or unnecessary?

In my opinion, it helps me to learn about the types, in that case, about Firebase's types.

CodePudding user response:

There is no right or wrong, it's matter of opinion and code styling. However, there are good arguments for avoiding explicitly declaring your types.

The effective TypeScript project has a nice chapter on explicitly annotating inferable types, and why it is considered a poor style.

My own personal opinion is that it makes your code harder to read and since most IDEs will show you the variable type when you mouse over it, an explicit declaration is redundant and noisy.

Still, it's one of those styling questions where's no 100% right or wrong answer.

  • Related