Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between Type Annotations and Type Inference?

Tags:

typescript

I was going through a TypeScript Tutorial and encountered with these terms: Type Annotations and Type Inference. I am not satisfied with the web explanation and not getting clear difference out of it. Need simple difference based explanation.

like image 654
Gourav Pokharkar Avatar asked Oct 15 '25 02:10

Gourav Pokharkar


1 Answers

Type inference is where the compiler works out the type on your behalf:

const a = 'Some value';

The variable a has an inferred type of string.

A type annotation is where you explicitly state the type:

const a: string = 'Some value';

You have specifically indicated that this should be a string with a type annotation (typically in the format : type).

The practical difference is that where types can be inferred, you save a great deal of typing without losing the benefits. In some cases, being explicit can be beneficial:

  • When creating an object with a literal value - as it catches mis-typed members
  • Function signatures - as parameter types are tricky to infer and return types will end up as a union of types found in return statements, so you might not realise you are returning different types in different cases
like image 163
Fenton Avatar answered Oct 18 '25 23:10

Fenton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!