Horje
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 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.




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Explain the Concept of Interfaces in TypeScript ? Explain the Concept of Interfaces in TypeScript ?
What is the use of Union Type in TypeScript ? What is the use of Union Type in TypeScript ?
How to implement Type narrowing in TypeScript? How to implement Type narrowing in TypeScript?
JavaScript Program to Search an Element in an Array JavaScript Program to Search an Element in an Array
How to Declare an Array in JavaScript ? How to Declare an Array in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14