Variables in TypeScript

Job-ready Online Courses: Knowledge Awaits – Click to Access!

The last article taught us about TypeScript’s Types, including Classes, Interfaces, and Generics. We’ll now examine TypeScript variables and investigate the many variables that can be applied in TypeScript applications.

What is a Variable in TypeScript?

A variable is a container for a value that can be used in a program. Many data kinds can be stored in variables, including numbers, strings, and objects. The “let” keyword, the variable name, and an optional type annotation are used in TypeScript to define variables.

let DataFlair_name: string = 'John';
let DataFlair_age: number = 30;
let DataFlair_isAdult: boolean = true;

#IMAGE#

Here, we have defined three variables: “DataFlair_name” of type string, “DataFlair_age” of type number, and “DataFlair_isAdult” of type boolean. TypeScript also provides the “const” keyword for defining constants that cannot be reassigned to a new value.

const PI: number = 3.14;

#IMAGE#

Here, we have defined a constant “PI” of the type number, with the value of 3.14.

In TypeScript, the var keyword can be used to define variables. Variables defined with var have function scope, which means they are accessible within the function in which they are defined.

Here is an example code that demonstrates the use of var keyword in TypeScript:

function DataFlair_greet() {
 var name = 'Alice';
 console.log('Hello, ' + name + '!');
}


DataFlair_greet(); // Output: Hello, Alice!
console.log(name); // Output: error, name is not defined

#IMAGE#

In this code, the var keyword is used to define a variable name inside the DataFlair_greet function. This variable is then used to display a greeting message on the console.

Note that the name variable is not accessible outside the DataFlair_greet function because it has a function scope. When we try to access it outside the function, we get an error message saying that the name is not defined.

It’s worth noting that the var keyword is not recommended in modern TypeScript code because it has some drawbacks. One drawback is that variables defined with var can be accessed before being declared, leading to confusing and error-prone code. Another disadvantage is that variables defined with var have function scope, which can make it harder to reason about code and can lead to bugs. Instead, the let and const keywords are recommended for defining variables in modern TypeScript code because they have block scope and are more predictable in their behavior.

Types of Variables in TypeScript

1. Number

The number data type represents both floating-point numbers and integers. Number types come in 1, 2, 3.5, 4.7, and other quantities. The keyword “number” in TypeScript defines the number type.

let DataFlair_age: number = 30;
let DataFlair_pi: number = 3.14;

2. String

The string data type represents a string of characters. Strings are included within single or double quotation marks. The string type is defined by the TypeScript keyword “string.”

let DataFlair_name: string = 'John';
let DataFlair_message: string = 'Hello, world!';

3. Boolean

The boolean data type represents a binary value that can either be true or false. TypeScript defines the boolean type using the keyword “boolean.”

let DataFlair_isAdult: boolean = true;
let DataFlair_hasChildren: boolean = false;

4. Array

A group of identically typed values is represented by the array data type. Arrays can hold an unlimited number of values of the same type and are defined using square brackets []. The keyword “Array” is used in TypeScript to define arrays.

let DataFlair_numbers: number[] = [1, 2, 3, 4, 5];
let DataFlair_fruits: string[] = ['apple', 'banana', 'orange'];

5. Tuple

The tuple data type represents an array with a fixed number of elements of different types. In TypeScript, tuples are defined using square brackets [], and the type of each element is specified in the order.

let DataFlair_person: [string, number] = ['John', 30];

Here, we have defined a tuple “DataFlair_person” with two elements: a string and a number. The first element is of type string and the second element is of type number.

6. Enum

The enum data type represents a set of named constants. Enums are defined using the keyword “enum” and can be assigned a set of named values.

enum DataFlair_Color {
 Red,
 Green,
 Blue,
}


let myColor: DataFlair_Color = DataFlair_Color.Red;

Here, we have defined an enum “DataFlair_Color” with three named values: Red, Green, and Blue. We have assigned the value of “Red” to the variable “myColor”.

7. Any

The any data type represents any value and can be used to disable type-checking for a variable. In TypeScript, the any type is defined using the keyword “any.”

let DataFlair_value: any = 'Hello, world!';
DataFlair_value = 10;
DataFlair_value = true;

Here, we have defined a variable “DataFlair_value” of type any. We can assign any value to this variable without type-checking.

8. Void

The void data type represents the absence of a value. In TypeScript, void is the return type for functions that do not return a value.

function DataFlair_logMessage(message: string): void {
 console.log(message);
}

Here, we have defined a function “DataFlair_logMessage” that takes a string parameter “message” and does not return a value.

9. Null and Undefined

The null and undefined data types represent the absence of a value. In TypeScript, null and undefined are treated as subtypes of all other types. That means you can assign null or undefined to a variable of any type.

let value1: null = null;
let value2: undefined = undefined;

Here, we have defined two variables, “value1” and “value2,” of types null and undefined, respectively.

Type Annotations in TypeScript

Developers can use type annotations in TypeScript to specify the type of a variable. A technique to explicitly declare a variable’s type and guarantee that it is used correctly throughout the application is through type annotations.

Type annotations are defined using the colon “:” symbol, followed by the data type. For example:

let DataFlair_age: number = 30;

Here, we have declared a variable “DataFlair_age” of the type number and assigned it the value of 30.

Type annotations can be used for function parameters and return types as well. For example:

function DataFlair_calculateSum(a: number, b: number): number {
 return a + b;
}

Redeclaration and Shadowing of Variables in TypeScript

In TypeScript, it is possible to re-declare variables and to create new variables with the same name as existing variables. This can lead to confusion and unexpected behavior, especially when variables are accessed from different parts of the code.

Here are some examples of re-declaration and shadowing of variables in TypeScript:

Re-declaration

Re-declaration occurs when a variable is declared more than once in the same scope.

For example:

let DataFlair_x = 10;
let DataFlair_x = 20; // Error: 'DataFlair_x' has already been declared.

In this code, the variable DataFlair_x is declared twice in the same scope, which causes an error.

Shadowing

Shadowing occurs when a new variable is declared with the same name as an existing variable in an inner scope.

For example:

let DataFlair_x = 10;


function foo() {
 let DataFlair_x = 20;
 console.log(DataFlair_x); // Output: 20
}


foo();
console.log(DataFlair_x); // Output: 10

Variable Scope in Typescript

In TypeScript, variable scope refers to the area of the program where a variable can be accessed. There are three types of variable scopes in TypeScript:

Global Scope:

Variables that are declared outside of any function or block have global scope, which means they can be accessed from anywhere in the program. Here’s an example:

let DataFlair_globalVar = 'Hello, world!';


function sayHello() {
 console.log(DataFlair_globalVar); // Output: Hello, world!
}


sayHello();
console.log(DataFlair_globalVar); // Output: Hello, world!

In this code, the variable DataFlair_globalVar is declared outside of any function, so it has global scope. It can be accessed from both the sayHello function and outside the function.

Local Scope:

Variables declared inside a function or block have local scope, meaning they can only be accessed from within that function or block. Here’s an example:

function DataFlair_sayHello() {
 let localVar = 'Hello, TypeScript!';
 console.log(localVar); // Output: Hello, TypeScript!
}


DataFlair_sayHello();
console.log(localVar); // Error: 'localVar' is not defined.

The variable localVar is declared inside the DataFlair_sayHello function in this code, so it has local scope. It can only be accessed from within the DataFlair_sayHello function, and attempting to access it outside it results in an error.

Block Scope:

Variables declared with let or const inside a block (such as a for loop or an if statement) have block scope, which means they can only be accessed from within that block. Here’s an example:

function DataFlair_count() {
 for (let i = 0; i < 5; i++) {
   console.log(i);
 }
 console.log(i); // Error: 'i' is not defined.
}
DataFlair_count();

In this code, the variable i is declared with let inside the for loop, so it has a block scope. It can only be accessed from within the for loop and attempting to access it outside the loop results in an error.

Understanding variable scope is essential in TypeScript programming, as it can help prevent naming conflicts and improve code organization. Using local and block scopes whenever possible is recommended, as this can make code more predictable and easier to maintain.

Type Assertation in TypeScript

Type assertion in TypeScript is a way to explicitly tell the TypeScript compiler that you know more about the type of a value than TypeScript does, and to change the type of a variable from one type to another.

There are two ways to perform type assertion in TypeScript:

1. Angle-bracket syntax

In this code, the angle-bracket syntax <string> is used to tell the TypeScript compiler that someValue is a string. This allows the .length property to be accessed as if it were a string, and the resulting value is assigned to DataFlair_strLength.

let DataFlair_strLength: number = (<string>someValue).length;

2. “as” syntax

let DataFlair_strLength: number = (someValue as string).length;

The “as” keyword is used in this code to perform type assertion. This has the same effect as the angle-bracket syntax but is often preferred in modern TypeScript code.

Type assertion can be helpful in cases where TypeScript’s type inference system cannot determine the correct type of a variable or when working with APIs that return values with unclear types.

However, using type assertion with care is important, as it can lead to runtime errors if the type assertion is incorrect. It’s always a good idea to double-check that the type assertion is correct and to use type guards or other techniques to ensure that the type is valid before performing operations on the value.

Conclusion

Developers have a great tool with TypeScript variables to define and use values in their applications. TypeScript variables can assist in catching issues at compile-time instead of runtime, lowering the likelihood of bugs in production code. Using TypeScript’s variables, developers may select the best data type for their use case and make sure their code is reliable and effective.

The many TypeScript variables, such as integer, string, boolean, array, tuple, enum, any, void, null, and undefined, were covered in this article. Explicitly stating the type of a variable, function argument, or return type can be done using type annotations, which were also covered in this discussion.

Developers may write more dependable, scalable, and maintainable code using TypeScript variables and annotations. You can accomplish your objectives and produce high-quality software by using TypeScript variables, whether developing a simple web application or a complex business system.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *