In this section, we will cover the basics of variables and data types in TypeScript. Understanding these concepts is crucial as they form the foundation of any TypeScript application.

  1. Introduction to Variables

Variables are used to store data that can be used and manipulated throughout your program. In TypeScript, you can declare variables using three keywords: var, let, and const.

1.1 var

  • Scope: Function-scoped.
  • Hoisting: Variables declared with var are hoisted to the top of their scope.
function exampleVar() {
    console.log(x); // undefined (due to hoisting)
    var x = 10;
    console.log(x); // 10
}
exampleVar();

1.2 let

  • Scope: Block-scoped.
  • Hoisting: Variables declared with let are not initialized until their definition is evaluated.
function exampleLet() {
    // console.log(y); // Error: Cannot access 'y' before initialization
    let y = 20;
    console.log(y); // 20
}
exampleLet();

1.3 const

  • Scope: Block-scoped.
  • Hoisting: Variables declared with const are not initialized until their definition is evaluated.
  • Immutability: The value of a const variable cannot be changed once it is assigned.
function exampleConst() {
    const z = 30;
    console.log(z); // 30
    // z = 40; // Error: Assignment to constant variable.
}
exampleConst();

  1. Data Types

TypeScript provides several built-in data types. Here are the most commonly used ones:

2.1 Primitive Types

Type Description Example
number Represents both integer and floating-point numbers. let num: number = 42;
string Represents text data. let str: string = "Hello";
boolean Represents true/false values. let isDone: boolean = false;
any Represents any type of data. let anything: any = 5;
void Represents the absence of a value. function logMessage(): void { console.log("Message"); }
null Represents a null value. let n: null = null;
undefined Represents an undefined value. let u: undefined = undefined;

2.2 Arrays

Arrays can be defined in two ways:

let numArray: number[] = [1, 2, 3];
let strArray: Array<string> = ["a", "b", "c"];

2.3 Tuples

Tuples allow you to express an array with a fixed number of elements whose types are known.

let tuple: [string, number];
tuple = ["hello", 10]; // OK
// tuple = [10, "hello"]; // Error

2.4 Enums

Enums allow you to define a set of named constants.

enum Color { Red, Green, Blue }
let c: Color = Color.Green;

2.5 Any

The any type is a powerful way to work with existing JavaScript, allowing you to opt-out of type-checking.

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

2.6 Union Types

Union types allow a variable to be one of several types.

let union: number | string;
union = 42; // OK
union = "Hello"; // OK
// union = true; // Error

  1. Type Inference

TypeScript can infer the type of a variable based on its value.

let inferredString = "This is a string"; // inferred as string
// inferredString = 42; // Error: Type 'number' is not assignable to type 'string'.

  1. Practical Examples

Example 1: Basic Variable Declarations

let age: number = 25;
const name: string = "John Doe";
let isStudent: boolean = true;

Example 2: Using Arrays and Tuples

let scores: number[] = [90, 85, 88];
let person: [string, number] = ["Alice", 30];

Example 3: Enum Usage

enum Direction { Up, Down, Left, Right }
let move: Direction = Direction.Up;

Example 4: Union Types

let id: number | string;
id = 101; // OK
id = "E101"; // OK

  1. Exercises

Exercise 1: Variable Declaration

Declare variables using let and const with appropriate types.

let city: string = "New York";
const pi: number = 3.14;
let isAvailable: boolean = true;

Exercise 2: Array and Tuple

Create an array of numbers and a tuple with a string and a number.

let numbers: number[] = [1, 2, 3, 4, 5];
let user: [string, number] = ["Alice", 25];

Exercise 3: Enum and Union Types

Define an enum for days of the week and a union type for a variable that can be either a string or a number.

enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
let today: Days = Days.Monday;

let code: number | string;
code = 123; // OK
code = "ABC"; // OK

  1. Summary

In this section, we covered:

  • The differences between var, let, and const.
  • Various data types in TypeScript, including primitive types, arrays, tuples, enums, and union types.
  • Type inference in TypeScript.
  • Practical examples and exercises to reinforce the concepts.

Understanding these basics will help you write more robust and type-safe code in TypeScript, which is essential for developing Angular applications. In the next section, we will dive into functions and arrow functions in TypeScript.

© Copyright 2024. All rights reserved