Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
Variables in TypeScript
Next article icon

TypeScript Type Annotations on Variables

Last Updated : 10 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
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 Annotations with Objects

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); 

Type Annotations with Objects

Type Annotations with Objects in TypeScript involve specifying the types of properties within an object. This approach ensures that objects adhere to a specific structure, preventing type-related errors and enhancing code maintainability.

Example: This TypeScript code defines a variable `person` with specific property types. It initializes `person` with values and logs its `name`, `age`, and `isAdmin` properties.

JavaScript
let person: {     name: string;     age: number;     isAdmin: boolean; } = {     name: "GFG",     age: 22,     isAdmin: false };  console.log(person.name); console.log(person.age); console.log(person.isAdmin);  

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.


Next Article
Variables in TypeScript

B

buhari12mushraf
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

Similar Reads

  • What is Type Annotations in TypeScript ?
    TypeScript Type Annotations allow developers to explicitly define the types of variables, functions, and other elements in the program. They help catch mistakes early by ensuring the right data type is used.They make the code easier to understand and follow.Type Annotations help avoid errors and mak
    3 min read
  • How to Get a Variable Type in TypeScript
    Understanding how to effectively ascertain the type of a variable in TypeScript is important for maintaining type safety and ensuring code robustness. In this article, we'll explore various approaches to determine the type of a variable, ranging from basic JavaScript operators to TypeScript-specific
    2 min read
  • TypeScript Return Type Annotations
    TypeScript Return Type Annotations allow you to define the expected return type of a function, enhancing code clarity and type safety. By specifying the return type (functionName(): ReturnType), you ensure the function returns the correct type, catching mismatches and reducing potential errors durin
    2 min read
  • TypeScript Parameter Type Annotations
    TypeScript Parameter type annotations are used to specify the expected data types of function parameters. They provide a way to explicitly define the types of values that a function expects as arguments. Parameter type annotations are part of TypeScript's static typing system, and they help catch ty
    2 min read
  • Variables in TypeScript
    Variables in TypeScript are used to store data values, acting as named memory locations that can hold numbers, strings, booleans, or other types of data. Variables can be declared using let, const, or var depending on the use case.They provide type safety by allowing you to define specific data type
    4 min read
  • How to Declare Variables in TypeScript ?
    In TypeScript, a variable can be defined by specifying the data type of the value it is going to store. It will store the values of the specified data type only and throws an error if you try to store the value of any other data type. You can use the colon syntax(:) to declare a typed variable in Ty
    2 min read
  • TypeScript - Type Annotations and Type Inference
    TypeScript is a superset of JavaScript that adds static typing, helping developers catch errors early. Two core features are type annotations- where developers explicitly define variable, parameter, and return types, and type inference, where TypeScript automatically deduces types based on values or
    5 min read
  • TypeScript Assertions Type
    TypeScript Assertions Type, also known as Type Assertion, is a feature that lets developers manually override the inferred or expected type of a value, providing more control over type checking in situations where TypeScript's automatic type inference may not be sufficient. Syntax let variableName:
    2 min read
  • Data types in TypeScript
    In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity. Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Pri
    3 min read
  • TypeScript Working with Generic Type Variables
    In TypeScript, working with generic type variables is a powerful feature that allows you to create functions and classes that can work with a variety of data types while maintaining type safety. Note: When you declare a generic function or class, you introduce a type variable enclosed in angle brack
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences