J
J
jedifa2021-07-26 12:23:07
typescript
jedifa, 2021-07-26 12:23:07

Should you explicitly define the type of a variable?

Can you please tell me whether it is worth explicitly defining the type of a variable or not? For example Here I explicitly defined the type, but the typescript can determine it itself, so is it worth defining it yourself or let the typescript determine it itself? Are there any differences at all? const a: number = 10;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-07-26
@jedifa

In this case, the differences will be only in the presence of this annotation.
I prefer not to annotate if ts itself can infer the type I need

D
Dmitry Belyaev, 2021-07-28
@bingo347

Can you please tell me whether it is worth explicitly defining the type of a variable or not?
In most cases, no, it's better to trust type inference, it will do it better.
const a: number = 10;
Are there any differences at all?
yes, since ts knows that const cannot be reassigned, and numbers are an immutable type, it will deduce here the literal type 10, which can be passed without problems both to number and to union from literal types containing 10
But you need to understand that type deduction works only from top to bottom, and because of this, there are cases when an explicit declaration is indispensable, for example:
// где-то есть
type SomeObject = { /* ... */ };
function getSomeObject(): SomeObject { /* ... */ }

// без явной декларации будет выведен тип null
let v: SomeObject | null = null;
setTimeout(() => {
  // без явной декларации типа для v здесь будет ошибка
  v = getSomeObject();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question