Open In App

TypeScript Type Annotations on Variables

Last Updated : 25 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript is a statically typed superset of JavaScript that brings the benefits of strong typing to the JavaScript ecosystem. One of its key features is the ability to add type annotations to variables, which helps developers catch type-related errors at compile time rather than runtime. In this article, we will explore TypeScript type annotations on variables, covering their syntax, and various approaches, and providing code examples for each.

Syntax:

let variableName: type;

Where-

  • variableName is the name of the variable
  • type is the type you want to assign to it.

These are the following approaches to use Type Annotation in TypeScript:

  • Type Annotations with Primitives
  • Type Annotations with Arrays

Type Annotation with Primitives

Type Annotations with Primitives in TypeScript involve explicitly specifying data types, such as numbers, strings, and booleans, for variables. This practice enhances code clarity and type safety by ensuring that variables can only store values conforming to their defined primitive types, thereby minimizing runtime errors.

Example:

Javascript




let pincode: number = 628204;
  
let city: string = "Chennai";
  
let isAvailabe: boolean = true;
  
console.log(pincode);
console.log(city);
console.log(isAvailabe);


Output:1

Type Annotations with Arrays

Type Annotations with Arrays in TypeScript refers to the practice of specifying the expected data type of elements within an array. This allows developers to create arrays that can only contain specific types of values, enhancing code reliability and readability while reducing the risk of type-related errors during development.

Example:

Javascript




let num: number[] = [10, 20, 30, 40, 55, 75];
  
let city: string[] = ["Chennai"
    "Gurugram", "Mumbai", "Hyderabad"];
  
console.log(num);
console.log(city);


Conclusion: TypeScript’s type annotations on variables are a powerful tool that enhances code quality by catching type-related errors early in the development process. By providing clear and concise information about the types of variables, developers can write more robust and maintainable code. Whether you are working with primitive types, custom types, or complex data structures, TypeScript’s type annotations can greatly improve your coding experience and contribute to more reliable software.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads