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
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Get a Variable Type in TypeScript
Next article icon

How to Declare Variables in TypeScript ?

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 TypeScript. You need to declare variables in this format because TypeScript is a statically typed language not a loosely typed language that is why you need to explicitly type the variables before assigning them values of a particular type.

Syntax:

const variable_name: data_type = value;

Example: The below code defines a variable with specified data types in TypeScript.

JavaScript
const var1: string = "GFG"; const var2: number = 35; console.log(var1); console.log(var2); 

Output:

"GFG"
35

Declaring Object Variables with Type Annotations

In TypeScript, you can also define the structure of an object by specifying the data type for each of its properties. This ensures that each property adheres to the declared type, and attempting to assign a value of an incorrect type will result in a compile-time error.

Syntax:

const variableName: { property1: dataType1; property2: dataType2; ... } = {
property1: value1,
property2: value2,
...
};

Example:

In this example, we'll define a Book object with properties for title, author, and publication year, each with specific types.

JavaScript
const book: { title: string; author: string; year: number } = {   title: "The Great Gatsby",   author: "F. Scott Fitzgerald",   year: 1925 };  console.log(book.title); // Output: "The Great Gatsby" console.log(book.year); // Output: 1925 

Purpose: This example illustrates how TypeScript allows for detailed structuring and typing of objects, which is crucial in larger, more complex applications where ensuring data integrity is essential. It helps developers prevent bugs related to incorrect data types, which can be a common issue in dynamically typed languages like JavaScript.


Next Article
How to Get a Variable Type in TypeScript

A

abhish8rzd
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-QnA
  • WebTech-FAQs

Similar Reads

  • 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
  • How to Create a Global Variable in TypeScript ?
    To create a global variable in TypeScript, we have multiple approaches. In this article, we are going to learn how to create a global variable in TypeScript. Below are the approaches used to create a global variable in TypeScript: Table of Content Using var, let or const at the Top LevelUsing window
    3 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 Access Enum Values in TypeScript ?
    Enums are a feature in TypeScript that help organize collections of related values. Accessing these values efficiently is crucial for clean, maintainable code. This guide provides a straightforward overview of different methods to access enum values in TypeScript, including bracket notation, dot not
    3 min read
  • How to declare a module in TypeScript ?
    A module is a piece of code that can be called or used in another code. There is nothing new about modules in Typescript. The concept of the module was introduced by JavaScript with ECMAScript 2015 release. Typescript is just re-using this feature. Will the code not work without Modules? Of course,
    8 min read
  • How to use express in typescript ?
    In this article, we will see how to use Express in TypeScript. The TypeScript is a superset of JavaScript that provides type notation with the JavaScript, so we can handle our server, and very scalable for the future. Express is web framework helps to create server-side handling with the help of Nod
    2 min read
  • How to Declare Multiple Variables in JavaScript?
    JavaScript variables are used as container to store values, and they can be of any data type. You can declare variables using the var, let, or const keywords. JavaScript provides different ways to declare multiple variables either individually or in a single line for efficiency and readability. Decl
    2 min read
  • How to get Value from a Dictionary in Typescript ?
    In TypeScript, a dictionary consists of objects that store data in the key-value pairs, and allow retrieval of values based on the specified keys. We can get value from a dictionary for the specific keys using various approaches. Table of Content Using Dot NotationUsing Bracket NotationUsing a Funct
    2 min read
  • How to declare nullable type in TypeScript ?
    In vanilla JavaScript, there are two primary data types: null and undefined. While TypeScript previously did not allow explicit naming of these types, you can now use them regardless of the type-checking mode. To assign undefined to any property, you need to turn off the --strictNullChecks flag. How
    2 min read
  • How to Get Value of Input in TypeScript ?
    In TypeScript, retrieving the value of an input element is a common task when building web applications. Whether you're handling form submissions, validating user input, or manipulating data based on user interactions, accessing input values is essential. The below approaches can be utilized to get
    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