Day 2: Mastering Basic Types in TypeScript – string, number, boolean, and More

·

4 min read

Welcome to Day 2 of your TypeScript journey! On Day 1, we set up TypeScript and explored its use cases. Today, we’ll dive into one of the foundational concepts of TypeScript: Basic Types. Understanding these types is crucial for writing type-safe and predictable code. Let’s explore the most commonly used basic types: string, number, boolean, and more.


Why Basic Types Matter

In JavaScript, variables can hold any type of value, which can lead to runtime errors and bugs. TypeScript introduces static typing, allowing you to define the type of data a variable can hold. By using basic types, you can catch errors during development, improve code readability, and make your applications more robust.


1. string

The string type is used to represent textual data. You can define a string using single quotes ('), double quotes ("), or backticks (` ) for template literals.

let userName: string = "John";
let msg: string = `Hello, ${userName}!`; // Template literal

Use Case: Use string for names, messages, and any text-based data.


2. number

In TypeScript, the number type represents both integers and floating-point values. Unlike some other languages, TypeScript doesn’t have separate types for integers and floats.

let age: number = 30;
let price: number = 19.99;

Use Case: Use number for ages, prices, quantities, and any numeric data.


3. boolean

The boolean type is used for true/false values. It’s commonly used in conditional logic and flags.

let isActive: boolean = true;
let isLoggedIn: boolean = false;

Use Case: Use boolean for toggles, conditions, and any true/false scenarios.


4. null and undefined

  • null represents an intentional absence of value.

  • undefined means a variable has been declared but not assigned a value.

let emptyValue: null = null;
let unassignedValue: undefined = undefined;

Use Case: Use null and undefined to handle missing or uninitialized values.


5. any

The any type is a wildcard that disables type checking. While it can be useful in certain scenarios, overusing any defeats the purpose of TypeScript.

let dynamicValue: any = "This can be anything";
dynamicValue = 42; // No error

Use Case: Use any sparingly, such as when working with third-party libraries or migrating JavaScript code to TypeScript.


6. void

The void type is used to indicate that a function does not return a value.

function logMessage(message: string): void {
    console.log(message);
}

Use Case: Use void for functions that perform actions but don’t return any value.


7. array

Arrays in TypeScript can be typed to ensure all elements are of the same type.

let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"]; // Generic syntax

Use Case: Use arrays for lists of items, such as user names, product IDs, or scores.


8. tuple

Tuples allow you to define an array with a fixed number of elements, each with a specific type.

let user: [string, number] = ["John", 30];

Use Case: Use tuples for fixed-length data structures, such as key-value pairs or coordinates.


9. enum

Enums are a way to define a set of named constants. They can be numeric or string-based.

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

Use Case: Use enums for predefined sets of values, such as status codes, directions, or colors.


10. object

The object type represents any non-primitive value (i.e., not string, number, boolean, etc.).

let user: object = { name: "John", age: 30 };

Use Case: Use object for complex data structures, such as user profiles or configuration objects.


Putting It All Together

Here’s an example that combines multiple basic types:

let person: { name: string, age: number, isActive: boolean } = {
    name: "Alice",
    age: 25,
    isActive: true,
};

function displayPersonInfo(person: { name: string, age: number, isActive: boolean }): void {
    console.log(`Name: ${person.name}, Age: ${person.age}, Active: ${person.isActive}`);
}

displayPersonInfo(person);

Conclusion

Basic types are the building blocks of TypeScript. By mastering string, number, boolean, and other basic types, you can write safer, more predictable, and maintainable code. As you progress in TypeScript, you’ll encounter more advanced types and patterns, but a solid understanding of these basics is essential.

Stay tuned for Day 3, where we’ll explore TypeScript Interfaces and Type Aliases!