DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Angular Fundamentals: Understanding TypeScript

Angular is built on TypeScript, a superset of JavaScript that introduces type safety, enabling developers to catch potential errors during development rather than at runtime. For developers familiar with TypeScript, this will be a familiar landscape, but if you're new to TypeScript, let's review some of its key features, which include static typing, interfaces, class properties, and accessibility levels (such as public and private). These features will be crucial throughout your journey in Angular development.

1. Static Typing

One of the core features of TypeScript is static typing. Unlike JavaScript, where variables can hold values of any type, TypeScript allows you to explicitly specify the types of variables, properties, and parameters.

In plain JavaScript, you might declare variables like this:

let name = "Whiskers";
let age = 5;
Enter fullscreen mode Exit fullscreen mode

In TypeScript, you can enforce data types by adding them to the variable declaration:

let name: string = "Whiskers";
let age: number = 5;
Enter fullscreen mode Exit fullscreen mode

With this setup, TypeScript ensures that name is always a string and age is always a number. If you try to assign an invalid value, such as a string to age, the TypeScript compiler will throw an error and the code won't compile.

This helps prevent potential bugs in your code by catching errors during development, giving you more confidence in your code’s correctness.

2. Interfaces

In TypeScript, interfaces allow you to define the shape of an object. This means that you can specify the required properties and their types, and TypeScript will ensure that any object assigned to this interface conforms to the shape.

For example, let's define an interface for a Cat object:

interface Cat {
    name: string;
    age: number;
    breed?: string; // optional property
}
Enter fullscreen mode Exit fullscreen mode

Now, when you create a cat object, it must adhere to this interface:

const fluffy: Cat = {
    name: "Fluffy",
    age: 3
};
Enter fullscreen mode Exit fullscreen mode

In this case, name and age are required fields, but breed is optional due to the ?. If you attempt to assign a Cat object that doesn’t conform to the interface, TypeScript will flag the issue:

const wrongCat: Cat = {
    name: "Whiskers",
    // missing 'age' property
};
Enter fullscreen mode Exit fullscreen mode

You can also make properties optional using the ? symbol, allowing flexibility when necessary, but still maintaining type safety.

3. Class Properties

TypeScript classes are similar to JavaScript classes but with additional type safety and features. For instance, you can explicitly declare types for class properties:

class Cat {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}
Enter fullscreen mode Exit fullscreen mode

This ensures that name is always a string and age is always a number. Additionally, you can define properties without initializing them in the constructor:

class Cat {
    name: string;
    breed?: string;
}
Enter fullscreen mode Exit fullscreen mode

TypeScript will ensure that these properties conform to the types you've declared, making your code more predictable and easier to debug.

4. Public and Private Accessibility

Another important feature in TypeScript is the ability to control accessibility to class members (properties and methods) using public and private access modifiers. By default, all class members are public in both JavaScript and TypeScript, meaning they can be accessed from anywhere. However, you can explicitly mark class members as private to restrict their accessibility to within the class.

For example:

class Cat {
    public name: string;
    private age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    speak() {
        return `Meow! I am ${this.name}`;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the name property is public, so it can be accessed outside the class, but the age property is private, so it can only be accessed within the class itself.

const whiskers = new Cat("Whiskers", 5);
console.log(whiskers.name); // Works fine
console.log(whiskers.age); // Error: 'age' is private
Enter fullscreen mode Exit fullscreen mode

Using private ensures encapsulation, preventing accidental changes or access to sensitive class data from outside the class.

5. Constructor Shorthand

TypeScript provides a handy shorthand for declaring and initializing properties via the constructor. Instead of manually declaring properties and assigning them in the constructor, you can declare them directly in the constructor’s parameter list.

Here’s a basic example:

class Cat {
    constructor(public name: string, private age: number) {}
}
Enter fullscreen mode Exit fullscreen mode

This code is functionally equivalent to the following:

class Cat {
    public name: string;
    private age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}
Enter fullscreen mode Exit fullscreen mode

The constructor shorthand simplifies code and reduces repetition. TypeScript automatically generates the necessary property declarations and assignments, saving you from writing extra code.

Conclusion

In this article, we covered some of the key TypeScript features that you'll frequently encounter in Angular development:

  • Static typing ensures that your variables, properties, and parameters have consistent types.
  • Interfaces allow you to define the shape of objects, adding further structure to your code.
  • Class properties give your classes explicit, type-safe declarations for fields.
  • Public and private accessibility ensures controlled access to class members, improving code encapsulation.
  • Constructor shorthand simplifies the process of initializing properties within classes.

These TypeScript features are fundamental to writing robust and maintainable Angular applications. Understanding them will help you leverage Angular's full potential as you build scalable, type-safe applications.

Next, let’s dive into preparing your development environment for Angular and set up the tools you'll need to get started!

Top comments (0)