Blog
JavaScript

Type Annotations in TypeScript: Explicitly Defining Types

Gain full control over types with clear annotations

Type annotations in TypeScript are used to explicitly specify the type of a variable, function parameter, or object property. This helps catch errors early, improves code readability, and ensures type safety.

Example:

typescript

Output:

typescript

In this example:

  • str is assigned the type string, so it will only accept string values.
  • num is a number type, ensuring it will only store numbers.
  • arr is an array that can hold both number and string types.

Function with Type Annotations

Type annotations in functions let you specify the expected types of parameters and the return value. This improves readability, enforces correctness, and helps catch errors early.

Now let's understand this with the help of example:

typescript

Output:

typescript
  • The greet function accepts a parameter name of type string and returns a string.
  • This ensures that both the input and output are of the expected types, preventing type-related errors.

Object with Type Annotations

Type annotations for objects define the structure and types of properties the object must have. This ensures type safety and prevents invalid assignments.

Now let's understand this with the help of example:

typescript

Output:

typescript
  • The person object is explicitly typed to have a name of type string and an age of type number.
  • This enforces the structure of the object, ensuring it adheres to the specified types.

Array with Type Annotations

Array type annotations explicitly specify the type of elements an array can hold. This helps catch errors and improves code readability.

Now let's understand this with the help of example:

typescript

Output:

text
  • The numbers array is annotated to contain only number elements.
  • This prevents the inclusion of elements of other types, maintaining type safety.

Class with Type Annotations

Type annotations in classes define the types of properties and method parameters/returns, ensuring that objects of the class follow a consistent structure. This improves type safety and code clarity.

Now let's understand this with the help of example:

typescript

Output:

typescript
  • The Rectangle class has width and height properties, both of type number.
  • The area method returns a number, representing the area of the rectangle.
avatar

0 Comments

No comments

Leave a Reply

avatar

Recent Post

Related Topics

    Feeds

      Don't miss what's next 👋

      Enjoyed this content? Leave your email to get notified when we publish new insights, tutorials, and updates — no spam, ever.