Type Annotations in TypeScript

Typescript uses type annotation to specify the data type of the variable, function, object, or function return value. It uses the syntax :[type], where type is the Typescript type. Once you have annotated an identifier to be of a certain type, you can only use it as that Type. The Typescript compiler throws an error if you use the identifier as a different type.

Type Annotations in TypeScript

TypeScript is JavaScript with Support for Types. It uses types to ensure that the variables are used correctly. To do that it needs to know the type of variable to enforce type checking. The typescript compiler is good enough to infer the type of the variable by its usage. This is called Type Inference. But it is not always possible to infer the type always. Hence we need to tell the compiler the type of the variable upfront. We do that by using the Type Annotations

Using the Type Annotation

We annotate a variable by using a colon (:) followed by its type. There can be a space after the colon. For example, the following shows how to use the type annotation in variable declaration.

Example of Type Annotation
Example of Type Annotations

Type Annotation in Variable declaration

The keyword after the colon i.e string/number/boolean is a Typescript type. By including a type, we are letting the compiler know the type of the variable. The compiler will throw an error in case we attempt to assign a value different than the specified type.

For Example, this will throw an error

The types are optional in Typescript. If you do not want to use the types, then annotate them with any as shown below

Then, the following example will not result in an error

Examples of Type Annotation

Arrays

The arrays are annotated using the string[] or Array as shown in the example below.

Function arguments & Return Types

Here, the function arguments are annotated with the number data type and so is the return type.

Anonymous Objects

Here, we are creating a object with two properties. The properties are annotated with the type number & string.

Union types

The union types are special. They allow a variable to be of either of two types. In the example, the id can be either a string or a number. The Typescript allows you to perform both string & arithmetic operations on the variable id.

Summary

Types are the reason why typescript exits. We annotate a variable, function, function return value, etc to let the compiler know how we intend to use it. we use the syntax :[type], where type is the Typescript datatype.

1 thought on “Type Annotations in TypeScript”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top