TypeScript - Type Annotations: A Beginner's Guide

Hello there, future coding superstar! ? Welcome to our exciting journey into the world of TypeScript and type annotations. As your friendly neighborhood computer science teacher, I'm thrilled to guide you through this adventure. Don't worry if you're new to programming – we'll start from the very beginning and work our way up together. So, grab your virtual backpack, and let's dive in!

TypeScript - Type Annotations

What Are Type Annotations?

Imagine you're packing for a trip. You have different bags for different items – one for clothes, one for toiletries, and one for electronics. Type annotations in TypeScript are like labels on these bags. They tell us and the computer what kind of "stuff" (data) we're dealing with.

In the world of TypeScript, type annotations are a way to explicitly tell the compiler what type of value a variable, function parameter, or object property can hold. It's like giving the computer a heads-up about what to expect.

Why Use Type Annotations?

  1. Catch errors early: They help us spot mistakes before running the code.
  2. Better code documentation: They make our code easier to understand.
  3. Improved development experience: They provide better autocomplete and IntelliSense in our code editors.

Now, let's look at different ways we can use type annotations.

Variable Type Annotations

When we create a variable in TypeScript, we can add a type annotation to specify what kind of value it should hold.

Basic Syntax

let variableName: Type = value;

Let's see some examples:

let myName: string = "Alice";
let myAge: number = 30;
let isStudent: boolean = true;

In these examples, we're telling TypeScript:

  • myName should only contain text (strings)
  • myAge should only be a number
  • isStudent should only be true or false (boolean)

If we try to assign a different type of value later, TypeScript will warn us:

myName = 42; // Error: Type 'number' is not assignable to type 'string'

Arrays and Special Types

We can also annotate arrays and use special types:

let favorites: string[] = ["pizza", "coding", "cats"];
let anything: any = "I can be anything!";
let maybe: unknown = 4;
  • string[] means an array of strings
  • any is a special type that can be anything (use sparingly!)
  • unknown is a safer alternative to any

Function Type Annotations

Functions can have type annotations for parameters and return values.

Basic Syntax

function functionName(param1: Type1, param2: Type2): ReturnType {
    // function body
}

Let's look at some examples:

function greet(name: string): string {
    return `Hello, ${name}!`;
}

function add(a: number, b: number): number {
    return a + b;
}

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

In these examples:

  • greet takes a string and returns a string
  • add takes two numbers and returns a number
  • logMessage takes a string but doesn't return anything (void)

Arrow Functions

Arrow functions can also have type annotations:

const multiply = (a: number, b: number): number => a * b;

Object Properties Type Annotations

When working with objects, we can annotate their properties.

Basic Syntax

let objectName: { property1: Type1; property2: Type2 } = {
    property1: value1,
    property2: value2
};

Let's see an example:

let user: { name: string; age: number; isAdmin: boolean } = {
    name: "Bob",
    age: 25,
    isAdmin: false
};

Here, we're defining an object with specific property types.

Interfaces for Complex Objects

For more complex objects, we can use interfaces:

interface Person {
    name: string;
    age: number;
    hobbies: string[];
    greet: () => void;
}

let employee: Person = {
    name: "Charlie",
    age: 30,
    hobbies: ["reading", "gaming"],
    greet: () => console.log("Hello!")
};

Interfaces help us define reusable object shapes.

Putting It All Together

Now that we've learned about different type annotations, let's see them in action with a more complex example:

interface Book {
    title: string;
    author: string;
    pages: number;
    isPublished: boolean;
}

function createBookList(books: Book[]): string[] {
    return books.map(book => `${book.title} by ${book.author}`);
}

const myBooks: Book[] = [
    { title: "TypeScript 101", author: "Code Wizard", pages: 200, isPublished: true },
    { title: "JavaScript Adventures", author: "JS Ninja", pages: 150, isPublished: false }
];

const bookTitles: string[] = createBookList(myBooks);
console.log(bookTitles);

This example combines various concepts we've learned:

  • We define an interface Book
  • We create a function createBookList that takes an array of Book objects and returns an array of strings
  • We create an array of Book objects
  • We call the function and store the result in a variable with the correct type annotation

Conclusion

Congratulations! You've just taken your first steps into the world of TypeScript type annotations. Remember, these annotations are like friendly signposts guiding you and your code to safety. They might seem a bit overwhelming at first, but with practice, they'll become second nature.

As you continue your coding journey, keep experimenting with different types and annotations. Don't be afraid to make mistakes – that's how we learn and grow!

Here's a handy table summarizing the type annotations we've covered:

Type Annotation Example Description
Basic Types let name: string = "Alice"; For simple values like strings, numbers, booleans
Array Types let numbers: number[] = [1, 2, 3]; For arrays of a specific type
Function Types function add(a: number, b: number): number For function parameters and return values
Object Types let user: { name: string; age: number } For object properties
Interface interface Person { name: string; age: number } For defining complex object shapes

Keep coding, stay curious, and remember – every master was once a beginner. Happy TypeScripting! ??‍??‍?

Credits: Image by storyset