Most programming languages are designed in a way to limit the amount of typing a user has to perform because well, people are naturally lazy. So when I decided to start learning TypeScript, which is a strict syntactical superset of JavaScript that adds optional static typing, I also want to be lazy at every opportunity I could find. In order to save my fingers some effort in TypeScript I first had to understand type annotation and inference.

Annotation

Type Annotation is simply when you tell Typescript what type of variable you want to define in same line you define it. There are twelve basic types in Typescript such as boolean, number, string, array, etc. In Figure 1, a variable a is defined but the type is not declared leading to a warning that the type is set to any, meaning the type can be any of the twelve that exist in Typescript. This is undesirable as it defeats the whole purpose of using Typescript which is to catch type errors in our code during development instead of at execution. This warning message can be simply resolved by defining the type at the variable declaration. In Figure 1, variable b is type annotated to have a number type.

Image for post

Figure 1: Type Annotation

Inference

Type inference is basically the opposite of type Annotation; instead of you directly telling Typescript which type of variable you are declaring, TypeScript figures out what type the variable should be based on the information you give it. This occurs when you declare a value the same time you declare a variable as seen in Figure 2. This will save you some keystrokes and will likely cover approximately 90% of your use cases.

Image for post

Figure 2: Type Inference

#typescript #annotations #inference

Typescript Type Declaration
1.05 GEEK