TypeScript - Variables and Datatypes
Last Updated :
17 Jan, 2025
TypeScript introduces static typing to make code more predictable and easier to debug. Variables are declared using let, const, or var to store data, while data types such as string, number, boolean, array, and enum ensure type safety and improve code reliability.
Variables
The variables can be declared using the following keywords
1. var
The var keyword is function-scoped, meaning the variable is accessible throughout the entire function in which it is declared.
- Function-scoped: The variable is accessible anywhere in the function where it is declared.
- Hoisted: The declaration is moved to the top of its scope, but not the initialization.
- Allows Redeclaration: A var variable can be redeclared within the same scope without errors.
JavaScript
function testVar() {
console.log(x); // Output: undefined (hoisting)
var x: number = 10;
console.log(x); // Output: 10
if (true) {
var y: number = 20;
}
console.log(y); // Output: 20 (not block-scoped)
}
testVar();
In this example
- The variable x is hoisted to the top of the function, so it can be accessed before its declaration but will be undefined.
- The value of x is updated, and the new value is logged.
- The variable y is declared inside an if block but is accessible outside of it due to var's function scope.
2. let
The let keyword is used to declare block-scoped variables, meaning the variable is only accessible within the block it is defined. It is the preferred choice for declaring variables that may need to change their value.
- Block-scoped: The variable is confined to the block {} in which it is declared.
- Mutable: The value of the variable can be updated after declaration.
- Avoids issues caused by var (e.g., hoisting bugs).
JavaScript
if (true) {
let score: number = 50;
console.log(score); // Output: 50
}
// console.log(score); // Error: score is not defined
let counter: number = 10;
counter += 5; // Allowed, as `counter` is mutable
console.log(counter); // Output: 15
In this example
- The variable score is defined inside an if block and is accessible only within that block.
- Trying to access score outside the block results in an error because let is block-scoped.
- The variable counter is mutable, so its value is successfully updated and logged.
3. Const
The const keyword is used to declare block-scoped, immutable variables. Once a const variable is assigned a value, it cannot be reassigned. However, objects declared with const can still have their properties modified.
- Block-scoped: Similar to let, it is confined to the block where it is defined.
- Immutable: The value of the variable cannot be reassigned after initialization.
- Requires Initialization: A const variable must be initialized at the time of declaration.
JavaScript
const MAX_LIMIT: number = 100;
console.log(MAX_LIMIT); // Output: 100
// MAX_LIMIT = 200; // Error: Cannot reassign a constant variable
const user = { name: "Ajay", age: 25 };
user.age = 26; // Allowed, as properties of objects can be modified
console.log(user); // Output: { name: "Ajay", age: 26 }
In this example
- The constant MAX_LIMIT is initialized with a value and cannot be reassigned.
- Attempting to reassign MAX_LIMIT results in an error.
- Even though user is a constant, the properties of the object it refers to can be modified.
Type Annotations in TypeScript
Type annotations explicitly specify the data type of a variable. While TypeScript can infer types based on assigned values, adding type annotations enhances code readability and prevents errors.
JavaScript
let score: number = 100;
let message: string = "Welcome to TypeScript!";
let isComplete: boolean = false;
In this example
- score is explicitly annotated as a number.
- message is explicitly annotated as a string.
- isComplete is explicitly annotated as a boolean.
TypeScript’s static typing ensures that variables only accept values of their specified types, reducing runtime errors.
More more detail read the article - Variables in TypeScript
Data Types
TypeScript offers a wide range of data types, ensuring that variables hold the expected type of data. Below are the common data types:
1. Primitive Types
Primitive Types are the most basic data types. They represent single values and are immutable, meaning their values cannot be changed once assigned.
- String: String is a primitive data type used to represent text values, enclosed in single, double, or backtick quotes. It supports template literals, string concatenation, and various string methods.
JavaScript
let name: string = "Riya";
let age: number = 25;
let isActive: boolean = true;
let nothing: null = null;
let notDefined: undefined;
Output
Riya
25
true
null
undefined
- Number: The number is a data type that represents both integer and floating-point values, including decimals, hexadecimal, binary, and octal values. It is a single type for all numerical values, unlike some languages that separate integers and floating-point numbers.
JavaScript
let age: number = 30;
let price: number = 19.99;
let hex: number = 0x1a;
let binary: number = 0b1010;
let octal: number = 0o12;
console.log(age);
console.log(price);
console.log(hex);
console.log(binary);
console.log(octal);
Output
30
19.99
26
10
10
- Boolean: The boolean is a data type that represents one of two values: true or false. It is typically used for conditional checks and logical operations.
JavaScript
let a : boolean = true;
let b : boolean = false;
console.log(a);
console.log(b);
Output
true
false
- Null and Undefined: The null represents the intentional absence of any object value, while undefined signifies a variable that has been declared but not assigned a value. Both are distinct types, with null explicitly set, and undefined automatically assigned.
JavaScript
let a : null = null;
let b : undefined;
console.log(a);
console.log(b);
Output
null
undefined
2. Complex Types
- Objects: Object represents any value that is not a primitive (like string, number, boolean, etc.), and it can hold a collection of key-value pairs or more complex data structures. It is often used to define more structured data types, such as objects with properties and methods.
JavaScript
let person: object = { name: "Alia", age: 30 };
console.log(person);
Output
{ name: "Alia", age: 30 }
- Array: An array is a collection of elements of the same type, defined using square brackets []. It allows storing multiple values in a single variable and supports various array methods for
JavaScript
let n : number[] = [1, 2, 3, 4, 5];
let s : string[] = ["Apple", "Banana", "Orange"];
console.log(n);
console.log(s);
Output
[1, 2, 3, 4, 5]
["Apple", "Banana", "Orange"]
- Tuple: A tuple is an ordered collection of elements with fixed types and a predefined length, allowing different types of values in specific positions. It is useful for representing data structures with a specific number of elements.
JavaScript
let a: [str, num] = ["Alia", 30];
let b: [num, num] = [10, 20];
console.log(a);
console.log(b);
Output
["Alia", 30]
[10, 20]e
- Enums: TypeScript Enums is a feature that lets you define a group of named constants, which can help you manage and understand your code more easily.
JavaScript
enum Color {
Red = 1,
Green = 2,
Blue = 3
}
let c : Color = Color.Green;
console.log(c);
console.log(Color[2]);
Output
2
Green
In this example
- Color: An enum representing colors with specific numeric values.
- c : A variable holding the enum value for Green.
- Color[2]: This retrieves the string value corresponding to the numeric value 2 in the Color enum, which is "Green".
3. Special Types
- Any: The
any
type allows a variable to hold any type of value, bypassing type checking. It provides flexibility but reduces the benefits of static typing and should be used sparingly.
JavaScript
let val: any = 5;
console.log(val);
val = "Hello, TypeScript!";
console.log(val);
val = [1, 2, 3];
console.log(val);
Output
5
Hello, TypeScript!
[1, 2, 3]
- Void: Void is used to represent the absence of any value, commonly used as the return type for functions that do not return anything. It indicates that a function's execution does not produce a result.
JavaScript
function msg(message: string): void {
console.log(message);
}
msg("Hello, TypeScript!");
Output
Hello, TypeScript!
- Union Types: Union Types allow a variable to hold values of multiple specified types, using the | (pipe) operator. It provides flexibility by enabling a variable to accept more than one type of value.
JavaScript
let val: string | number;
val = "Hello, TypeScript!";
console.log(val);
val = 42;
console.log(val);
Output
Hello, TypeScript!
42
Similar Reads
TypeScript Type Annotations on Variables 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 ar
3 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.Prim
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
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.Syntaxlet variableName: As
2 min read
What is the Record Type in TypeScript ? In TypeScript, the Record type is a utility type that represents an object type with keys and values of a specific type. It is often used when you want to define a type for the keys and values of an object. In this article, we will learn what is the Record type in TypeScript. Syntax:Record<Keys,
2 min read
TypeScript Generic Object Types TypeScript Generic Object Types allow you to create flexible and reusable type definitions for objects. These generic types can work with different shapes of objects while providing type safety, ensuring your code is both robust and adaptable. They are particularly useful for creating functions or c
3 min read