Answer the question
In order to leave comments, you need to log in
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
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
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.
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 10const a: number = 10;
Are there any differences at all?
// где-то есть
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 questionAsk a Question
731 491 924 answers to any question