You are currently viewing TypeScript Variables: A Comprehensive Guide with Examples

TypeScript Variables: A Comprehensive Guide with Examples

In TypeScript, variables are used to store data values. They play a crucial role in programming by allowing developers to manipulate and work with data dynamically. In this tutorial, we’ll explore the fundamentals of variables in TypeScript, including their types, declarations, and usage.

Variable Declarations

In TypeScript, you can declare variables using three keywords: var, let, and const.

1. var Keyword

var num: number = 10;
var greeting: string = "Hello, TypeScript!";

Variables declared with var are function-scoped and can be reassigned.

2. let Keyword

let age: number = 25;
let name: string = "John";

Variables declared with let are block-scoped and can be reassigned.

3. const Keyword

const PI: number = 3.14;
const appName: string = "MyApp";

Variables declared with const are also block-scoped but cannot be reassigned once initialized.

Variable Types

TypeScript is a statically typed language, meaning variables can have types assigned to them.

1. Basic Types

let num: number = 10;
let str: string = "Hello";
let bool: boolean = true;
let arr: number[] = [1, 2, 3];

2. Custom Types

type Point = {
    x: number;
    y: number;
};

let point: Point = { x: 10, y: 20 };

Variable Usage

Variables in TypeScript can be used in various contexts, including arithmetic operations, function parameters, and object properties.

Arithmetic Operations

let a: number = 10;
let b: number = 5;
let sum: number = a + b; // sum = 15

Function Parameters

function greet(name: string): void {
    console.log("Hello, " + name + "!");
}

greet("Alice"); // Output: Hello, Alice!

Object Properties

type Person = {
    name: string;
    age: number;
};

let person: Person = {
    name: "John",
    age: 30
};

console.log(person.name); // Output: John
console.log(person.age); // Output: 30

Conclusion

Understanding variables is essential for any TypeScript developer. In this tutorial, we covered variable declarations, types, and usage with practical examples. Mastering variables will empower you to write more efficient and maintainable TypeScript code. Start applying what you’ve learned and experiment with different scenarios to deepen your understanding. Happy coding!

Leave a Reply