TypeScript Beginner Tutorial 6 | Basic Variable Types 2

4 min read 11 months ago
Published on Sep 11, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will explore basic variable types in TypeScript, building upon foundational concepts essential for any beginner. This guide will cover arrays, tuples, enums, the unknown type, the any type, void, and union types. Understanding these types is crucial for effective programming in TypeScript and will help you write more robust and maintainable code.

Step 1: Working with Arrays

Arrays in TypeScript are used to store collections of values. Here's how to declare and initialize arrays:

  • Using shorthand notation:

    let list1: number[] = [1, 2, 3];
    
  • Using generic array type:

    let list2: Array<number> = [1, 2, 3];
    

Practical Tip: Always specify the type of values your array will hold to leverage TypeScript's type-checking capabilities.

Step 2: Understanding Tuples

Tuples allow you to store a fixed number of values with different types. Here's how to declare and initialize a tuple:

  • Declaration:

    let x: [string, number];
    
  • Initialization:

    x = ["hello", 10]; // Correct
    x = [10, "hello"]; // Error: Type 'number' is not assignable to type 'string'
    
  • Accessing Tuple Values:

    console.log(x[0].substring(1)); // Outputs: "ello"
    

Common Pitfall: Ensure the types match when initializing a tuple to avoid type errors.

Step 3: Using Enums

Enums provide a way to give friendly names to sets of numeric values. Here’s how to define and use an enum:

  • Defining an Enum:

    enum Color {
        Red = 3,
        Green,
        Blue,
    }
    
  • Using an Enum:

    let c: Color = Color.Green;
    console.log(c); // Outputs: 4 (Green is the fourth member, starting from 3)
    

Practical Tip: You can manually set the value of any enum member to control its numbering.

Step 4: The Unknown Type

The unknown type is used when the type of a variable is not known. Here's how to declare and use it:

  • Declaration:

    let notSure: unknown = 4;
    
  • Using the Unknown Type:

    // notSure(); // Error: notSure is of type unknown
    // notSure.toUpperCase(); // Error: notSure is of type unknown
    (notSure as string).toUpperCase(); // Correct way to assert type
    

Practical Tip: Use unknown when you want to signify that a variable could be of any type without losing type safety.

Step 5: The Any Type

The any type allows you to opt-out of type checking. Here’s how to declare an any type variable:

  • Declaration:

    let anyValue: any = 10;
    
  • Assigning Different Types:

    anyValue = true; // No error
    anyValue = 'hello'; // No error
    anyValue(); // No error
    anyValue.toUpperCase(); // No error
    

Common Pitfall: While using any offers flexibility, it can lead to runtime errors due to lack of type safety. Use it sparingly.

Step 6: The Void Type

The void type is used for functions that do not return any value. Here’s how to define such a function:

  • Function Declaration:
    function warnUser(): void {
        console.log("This is my warning message");
    }
    

Practical Tip: Use void as the return type for functions intended only for their side effects.

Step 7: Union Types

Union types allow a variable to hold multiple types. Here’s how to declare a union type:

  • Declaration:

    let peopleAllowed: number | boolean;
    
  • Assigning Values:

    peopleAllowed = 10; // Valid
    peopleAllowed = false; // Valid
    

Practical Tip: Use union types when dealing with values that can come from external sources or user inputs.

Conclusion

In this tutorial, we've covered the essential variable types in TypeScript, including arrays, tuples, enums, unknown, any, void, and union types. These types are fundamental for writing clean and effective TypeScript code. To further your understanding, experiment with these types in your own projects and refer to TypeScript documentation for advanced topics. Happy coding!