In TypeScript, variables are used to store values that can be referenced and manipulated throughout your code. TypeScript offers three main ways to declare variables: let, const, and var. Each has different behavior when it comes to reassigning values and scoping, allowing us to write more reliable and understandable code.
Types of Variable Declarations
In TypeScript, we can declare variables in several ways.
1. Declare Type and Value in a Single Statement
typescript
let name: string = 'Amit';
const age: number = 25;
- Type and value are defined together.
- name is a variable of type string.
- age is a constant of type number.
2. Declare Type Without Value
typescript
let city: string;
console.log(city);
- Only the type is defined; the value is undefined by default.
3. Declare Value Without Type
JavaScript
let country = 'India';
console.log(country);
- The type is inferred as string, and the value is initialized to 'India'.
Variable Declaration Keywords in TypeScript
TypeScript allows you to declare variables using three keywords: var, let, and const. Here's a breakdown of how each works:
1. var
var is function-scoped and can lead to unexpected behavior due to hoisting. It’s accessible throughout the function in which it’s declared but has function-level scoping.
JavaScript
function testVar() {
var globalVar = "I am a function-scoped variable";
console.log(globalVar);
}
testVar();
Output
I am a function-scoped variable
In this example
- Function testVar() is declared.
- Inside the function, a variable globalVar is declared with var.
- var gives it function scope, meaning it's only available inside the function.
- console.log(globalVar) prints the value: "I am a function-scoped variable".
- The function is called with testVar(), and the output is shown.
- Outside the function, globalVar isn't accessible.
Note => Avoid using var in modern TypeScript due to its unpredictable behavior.
2. let
let provides block-level scoping, meaning it is confined to the block (i.e., loop or condition) in which it is declared. It helps prevent redeclaration within the same scope and reduces issues related to hoisting.
JavaScript
let count = 5;
if (count > 0) {
let message = "Count is positive";
console.log(message);
}
// console.log(message); // Error: message is not accessible here
Output
Count is positive
In this example
- let count = 5; declares a variable count.
- Inside the if block, a new variable message is declared with let.
- let gives message block-level scope, meaning it's only available within the if block.
- console.log(message); prints "Count is positive" inside the block.
- Outside the block, trying to access message results in an error because it’s out of scope.
3. const
Similar to let in terms of scoping, const is used for variables that should not be reassigned after their initial value. Attempting to reassign a const variable results in a compile-time error.
JavaScript
const country = "India";
// country = "USA"; // Error: Cannot assign to 'country' because it is a constant
console.log(country);
Output
India
In this example
- const country = "India"; declares a constant variable country and assigns it the value "India".
- Since it's declared with const, it cannot be reassigned.
- Attempting to change its value with country = "USA"; results in an error.
- console.log(country); prints "India" to the console.
Note:
- Variable names can contains alphabets both Upper-case as well as Lower-case and digits also.
- Variable names can’t start with a digit.
- We can use _ and $ special characters only, apart from these other special characters are not allowed.
Type Annotations in TypeScript
Type annotations allow you to explicitly define the type of a variable, improving code clarity and reducing the risk of errors. Using explicit types helps TypeScript catch errors during development and ensures better maintainability.
Now let's understand this with the help of example:
JavaScript
let userName: string = "Arjun";
let age: number = 25;
let isActive: boolean = true;
function greetUser(name: string, age: number): string {
return `Hello, ${name}! You are ${age} years old.`;
}
let greeting = greetUser(userName, age);
console.log(greeting);
Output
Hello, Arjun! You are 25 years old.
In this example
- userName: string specifies that the userName variable must hold a string value.
- age: number specifies that the age variable must hold a number value.
- isActive: boolean specifies that isActive must be a boolean.
- The function greetUser(name: string, age: number) uses type annotations for both parameters and the return type to ensure type safety.
Variable Scopes in TypeScript
Understanding variable scope is crucial for managing the accessibility and lifespan of variables in TypeScript. There are three main types of scopes:
1. Local Scope
Variables declared within a function or block are accessible only within that function or block.
JavaScript
function testLocalScope() {
let localVar = "I am local";
console.log(localVar);
}
// console.log(localVar); // Error: localVar is not defined outside the function
Output
I am local
In this example
- The function testLocalScope() is declared.
- Inside the function, a variable localVar is declared with let.
- let gives localVar block-level scope, meaning it’s only available inside the function.
- console.log(localVar); inside the function prints "I am local".
- Trying to access localVar outside the function results in an error because it’s out of scope.
2. Global Scope
Variables declared outside any function or block are accessible throughout the entire program.
JavaScript
let globalVar = 10;
function displayGlobalVar() {
console.log(globalVar);
}
displayGlobalVar();
Output
10
In this example
- A variable globalVar is declared outside the function and assigned the value 10.
- The function displayGlobalVar() is declared.
- Inside the function, console.log(globalVar) prints the value of globalVar, which is 10.
- The function displayGlobalVar() is called, showing the value of globalVar.
3. Class Scope
Variables declared within a class are accessible to all members (methods) of that class.
JavaScript
class Employee {
salary: number = 50000;
printSalary(): void {
console.log(`Salary: ${this.salary}`);
}
}
const emp = new Employee();
emp.printSalary();
Output
50000
In this example
- The class Employee has: A property salary set to 50000. A method printSalary() that prints the salary.
- An object emp is created from the Employee class.
- Calling emp.printSalary() prints the salary.
Now let's understand variables with this example:
JavaScript
let globalVar: number = 10;
class Geeks {
private classVar: number = 11;
assignNum(): void {
let localVar: number = 12;
console.log('Local Variable: ' + localVar);
}
}
console.log('Global Variable: ' + globalVar);
let obj = new Geeks();
obj.assignNum();
- globalVar is a global variable, accessible throughout the program.
- classVar is a private class-level variable, accessible only within the Geeks class.
- localVar is a local variable, accessible only within the assignNum method.
Output:
Global Variable: 10
Local Variable: 12
Conclusion
In TypeScript, variables are essential for storing and manipulating data. By using let, const, and var, TypeScript allows us to define variables with different scoping and reassignment rules, enhancing code reliability. Understanding type annotations helps catch errors early, improving code clarity
Similar Reads
TypeScript Tutorial TypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
TypeScript Basics
Introduction to TypeScriptTypeScript is a syntactic superset of JavaScript that adds optional static typing, making it easier to write and maintain large-scale applications.Allows developers to catch errors during development rather than at runtime, improving code reliability.Enhances code readability and maintainability wit
5 min read
Difference between TypeScript and JavaScriptEver wondered about the difference between JavaScript and TypeScript? If you're into web development, knowing these two languages is super important. They might seem alike, but they're actually pretty different and can affect how you code and build stuff online.In this article, we'll break down the
4 min read
How to install TypeScript ?TypeScript is a powerful language that enhances JavaScript by adding static type checking, enabling developers to catch errors during development rather than at runtime. As a strict superset of JavaScript, TypeScript allows you to write plain JavaScript with optional extra features. This guide will
3 min read
Hello World in TypeScriptTypeScript is an open-source programming language. It is developed and maintained by Microsoft. TypeScript follows javascript syntactically but adds more features to it. It is a superset of javascript. The diagram below depicts the relationship:Typescript is purely object-oriented with features like
3 min read
How to execute TypeScript file using command line?TypeScript is a statically-typed superset of JavaScript that adds optional type annotations and compiles to plain JavaScript. It helps catch errors during development. To execute a TypeScript file from the command line, compile it using tsc filename.ts, then run the output JavaScript file with node.
2 min read
Variables in TypeScriptIn TypeScript, variables are used to store values that can be referenced and manipulated throughout your code. TypeScript offers three main ways to declare variables: let, const, and var. Each has different behavior when it comes to reassigning values and scoping, allowing us to write more reliable
6 min read
What are the different keywords to declare variables in TypeScript ?Typescript variable declarations are similar to Javascript. Each keyword has a specific scope. Let's learn about variable declarations in this article. In Typescript variables can be declared by using the following keywords:varlet constVar keyword: Declaring a variable using the var keyword.var vari
4 min read
Identifiers and Keywords in TypeScriptIn TypeScript, identifiers are names used for variables, classes, or methods and must follow specific naming rules. Keywords are reserved words with predefined meanings and cannot be used as identifiers. Comments, both single-line and multi-line, enhance code readability and are ignored during code
2 min read
TypeScript primitive types
Data types in TypeScriptIn 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.Prim
3 min read
TypeScript NumbersTypeScript Numbers refer to the numerical data type in TypeScript, encompassing integers and floating-point values. The Number class in TypeScript provides methods and properties for manipulating these values, allowing for precise arithmetic operations and formatting, enhancing JavaScript's native n
4 min read
TypeScript StringIn TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string. TypeSc
4 min read
Explain the concept of null and its uses in TypeScriptNull refers to a value that is either empty or a value that doesn't exist. It's on purpose that there's no value here. TypeScript does not make a variable null by default. By default unassigned variables or variables which are declared without being initialized are 'undefined'. To make a variable nu
3 min read
TypeScript Object types
What are TypeScript Interfaces?TypeScript interfaces define the structure of objects by specifying property types and method signatures, ensuring consistent shapes and enhancing code clarity.Allow for optional and read-only properties for flexibility and immutability.Enable interface inheritance to create reusable and extendable
4 min read
TypeScript classA TypeScript class is a blueprint for creating objects, encapsulating properties (data) and methods (behavior) to promote organization, reusability, and readability.Supports inheritance, allowing one class to extend another and reuse functionality.Provides access modifiers (public, private, protecte
4 min read
How enums works in TypeScript ?In this article, we will try to understand all the facts which are associated with enums in TypeScript. TypeScript enum: TypeScript enums allow us to define or declare a set of named constants i.e. a collection of related values which could either be in the form of a string or number or any other da
4 min read
TypeScript TuplesIn JavaScript, arrays consist of values of the same type, but sometimes we need to store a collection of values of different types in a single variable. TypeScript offers tuples for this purpose. Tuples are similar to structures in C programming and can be passed as parameters in function calls.Tupl
3 min read
TypeScript other types
What is any type, and when to use it in TypeScript ?Any is a data type in TypeScript. Any type is used when we deal with third-party programs and expect any variable but we don't know the exact type of variable. Any data type is used because it helps in opt-in and opt-out of type checking during compilation. In this article, we will see what is any
3 min read
How to Create an Object in TypeScript?TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
What is an unknown type and when to use it in TypeScript ?In Typescript, any value can be assigned to unknown, but without a type assertion, unknown can't be assigned to anything but itself and any. Similarly, no operations on an unknown are allowed without first asserting or restricting it down to a more precise type. Â similar to any, we can assign any va
3 min read
Explain the purpose of never type in TypeScriptIn Typescript when we are certain that a particular situation will never happen, we use the never type. For example, suppose you construct a function that never returns or always throws an exception then we can use the never type on that function. Never is a new type in TypeScript that denotes value
3 min read
TypeScript combining types
TypeScript Assertions
TypeScript Functions
TypeScript interfaces and aliases
TypeScript classes
How to Extend an Interface from a class in TypeScript ?In this article, we will try to understand how we to extend an interface from a class in TypeScript with the help of certain coding examples. Let us first quickly understand how we can create a class as well as an interface in TypeScript using the following mentioned syntaxes: Syntax:Â This is the s
3 min read
How to Create an Object in TypeScript?TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
How to use getters/setters in TypeScript ?In TypeScript, getters and setters provide controlled access to class properties, enhancing encapsulation and flexibility.Getters allow you to retrieve the value of a property with controlled logic.Setters enable controlled assignment to properties, often including validation or transformations.Java
5 min read
TypeScript InheritanceInheritance is a fundamental concept in object-oriented programming (OOP). It allows one class to inherit properties and methods from another class. The class that inherits is called the child class, and the class whose properties and methods are inherited is called the parent class. Inheritance ena
3 min read
When to use interfaces and when to use classes in TypeScript ?TypeScript supports object-oriented programming features like classes and interfaces etc. classes are the skeletons for the object. it encapsulates the data which is used in objects. Interfaces are just like types for classes in TypeScript. It is used for type checking. It only contains the declarat
4 min read
Generics Interface in typescript"A major part of software engineering is building components that not only have well-defined and consistent APIs but are also reusable. " This sentence is in the official documentation we would start with. There are languages that are strong in static typing & others that are weak in dynamic typ
5 min read
How to use property decorators in TypeScript ?Decorators are a way of wrapping an existing piece of code with desired values and functionality to create a new modified version of it. Currently, it is supported only for a class and its components as mentioned below: Class itselfClass MethodClass PropertyObject Accessor ( Getter And Setter ) Of C
4 min read