DEV Community

Cover image for TypeScript Fundamentals: A Beginner's Guide (2025) ✅
Forrester Terry
Forrester Terry

Posted on

TypeScript Fundamentals: A Beginner's Guide (2025) ✅

TypeScript has caused endless debates among developers. Some see it as a bureaucratic roadblock to the freedom of JavaScript, while others hail it as a beacon of light in the trenches of loosely typed code. Love it or hate it, TypeScript is here to stay — and once you get to know it, you might just find it’s not a burden but a blessing for your projects.

In this series we will explore TypeScript and cover the basics -- as well as some tricks and troubleshooting tips.

1. Introduction

What is TypeScript?

TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. In simpler terms, it’s JavaScript with extra features that help you catch errors early and write better, more maintainable code.

Think of TypeScript as a friendly assistant who double-checks your work before you submit it. It lets you:

  • Spot errors while you’re coding, not after you’ve deployed.
  • Write code that’s easier to read and understand.
  • Scale your projects without losing track of how things connect.

Why Use TypeScript?

Let’s get practical. Why should you care about TypeScript when JavaScript already works?

Real Benefits:

  1. Catch Errors Early: Avoid common pitfalls, like passing the wrong data type to a function.
   function greet(name: string) {
     return `Hello, ${name}!`;
   }
   greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Enter fullscreen mode Exit fullscreen mode
  1. Autocompletion & Documentation: Modern editors (like VS Code) provide rich autocomplete suggestions and documentation as you type.

  2. Code Scalability: TypeScript’s features shine in larger projects where maintaining consistency is key.

  3. Improved Team Collaboration: Clear types make it easier for team members to understand your code at a glance.

I have found TypeScript to be particularly helpful for planning out bigger apps; understanding what types of data I will be dealing with and what data my functions take/return.

Prerequisites

Before diving in, ensure you have basic JavaScript knowledge. You should be familiar with:

  • Variables and data types (e.g., let, const, string, number)
  • Functions
  • Arrays and objects

If you’re not confident yet, take some time to review JavaScript basics.


2. Setting Up Your Environment

Installing TypeScript

TypeScript is a tool that requires installation to get started. With just a few steps, you can prepare your environment to begin coding in TypeScript. Here’s how to do it:

To start using TypeScript, you’ll need Node.js installed. Once you have that:

  1. Install TypeScript globally:
   npm install -g typescript
Enter fullscreen mode Exit fullscreen mode
  1. Verify the installation:
   tsc --version
Enter fullscreen mode Exit fullscreen mode

Setting Up VS Code

VS Code is one of the most popular editors for TypeScript development. It provides a range of features and extensions that make coding easier and more efficient. Let’s set it up:

VS Code is the go-to editor for TypeScript developers. Here’s how to set it up:

  1. Install VS Code: Download here
  2. Add these helpful extensions:
    • ESLint: For linting your TypeScript code.
    • Prettier: For consistent code formatting.
    • TypeScript Hero: For improved productivity.

Creating Your First TypeScript Project

Getting hands-on is the best way to learn TypeScript. This section guides you through setting up your first project, from creating files to running your code.

  1. Create a new folder for your project and navigate into it:
   mkdir typescript-starter
   cd typescript-starter
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a new project:
   npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Add TypeScript:
   npm install --save-dev typescript
Enter fullscreen mode Exit fullscreen mode
  1. Create a tsconfig.json file:
   npx tsc --init
Enter fullscreen mode Exit fullscreen mode
  1. Write your first TypeScript file:
   echo "console.log('Hello, TypeScript!');" > index.ts
Enter fullscreen mode Exit fullscreen mode
  1. Compile and run:
   npx tsc index.ts
   node index.js
Enter fullscreen mode Exit fullscreen mode

You’ve just written and compiled your first TypeScript program!


3. Basic Types Overview

TypeScript’s power lies in its type system. Let’s explore some basic types:

Primitive Types

Primitive types are the building blocks of TypeScript’s type system. They include basic data types like strings, numbers, and booleans. Here’s a quick look at how to use them:

  1. string:
   let name: string = "Alice";
Enter fullscreen mode Exit fullscreen mode
  1. number:
   let age: number = 25;
Enter fullscreen mode Exit fullscreen mode
  1. boolean:
   let isStudent: boolean = true;
Enter fullscreen mode Exit fullscreen mode

Advanced Types

In addition to primitives, TypeScript supports more complex types like arrays, tuples, and special types like any and unknown. These types make your code flexible while maintaining safety.

  1. Arrays:
   let scores: number[] = [90, 85, 88];
Enter fullscreen mode Exit fullscreen mode
  1. Tuples:
   let user: [string, number] = ["Alice", 25];
Enter fullscreen mode Exit fullscreen mode
  1. any (use sparingly):
   let data: any = "Could be anything";
Enter fullscreen mode Exit fullscreen mode
  1. unknown (safer than any):
   let value: unknown = 10;
Enter fullscreen mode Exit fullscreen mode
  1. void (functions that return nothing):
   function logMessage(message: string): void {
     console.log(message);
   }
Enter fullscreen mode Exit fullscreen mode
  1. null and undefined:
   let something: null = null;
   let nothing: undefined = undefined;
Enter fullscreen mode Exit fullscreen mode

4. First Steps with Type Annotations

Type Annotations in TypeScript allow developers to specify the type of a variable, parameter, or function return value. This ensures that the code adheres to a defined structure, making it easier to catch errors during development and maintain consistency throughout the project.

As you write your code as you normally do, take note of the features below that you can integrate

Basic Variable Typing

Set types for your variables so that they are always set to the right thing, and the rest of the app understands what they are.

let firstName: string = "Alice";
let age: number = 30;
Enter fullscreen mode Exit fullscreen mode

Function Parameter Typing

Similarly, for functions you can define the types for the arguments, as well define the type for the return.

// Note the 'number' keywords for each param
function add(a: number, b: number): number { 
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Return Type Annotations

// Note the 'string' keyword at the end
function greet(name: string): string { 
  return `Hello, ${name}!`;
}
Enter fullscreen mode Exit fullscreen mode

Practical Example: User Profile

TypeScript allows you to declare your own types to better structure and enforce rules in your code. By using type or interface, you can define custom types for objects, functions, or even unions. This not only makes your code more robust but also improves readability and consistency in larger projects.

interface UserProfile = {
  name: string;
  age: number;
  isActive: boolean;
};

const user: UserProfile = {
  name: "Alice",
  age: 25,
  isActive: true,
};
Enter fullscreen mode Exit fullscreen mode

5. Quick Start with Interfaces

Basic Syntax

Interfaces in TypeScript define the structure of objects, ensuring they have specific properties and types. This section shows you how to create and use them:

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "Bob",
  age: 30,
};
Enter fullscreen mode Exit fullscreen mode

Optional Properties

Sometimes, not all properties in an object are required. TypeScript lets you define optional properties in interfaces to handle such cases gracefully.

interface Product {
  name: string;
  price?: number;
}

const item: Product = { name: "Notebook" };
Enter fullscreen mode Exit fullscreen mode

Readonly Properties

Readonly properties are useful when you want to ensure certain values cannot be changed after they are set. Here’s how to use them in interfaces:

interface Book {
  readonly title: string;
}

const myBook: Book = { title: "TypeScript Handbook" };
// myBook.title = "Another Title"; // Error: Cannot assign to 'title'.
Enter fullscreen mode Exit fullscreen mode

Real-World Example: API Response

Using interfaces to type API responses ensures you handle data from servers safely and effectively. Here’s a practical example:

interface ApiResponse {
  data: unknown;
  status: number;
}
Enter fullscreen mode Exit fullscreen mode

6. Practice Project: Building a Simple Todo List

Practice is key to mastering TypeScript. In this project, you’ll create a simple todo list application that leverages the features you’ve learned so far:

  1. Create a Todo type:
   interface Todo {
     id: number;
     title: string;
     completed: boolean;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Build a simple array of todos:
   const todos: Todo[] = [
     { id: 1, title: "Learn TypeScript", completed: false },
   ];
Enter fullscreen mode Exit fullscreen mode
  1. Add some functions to add todos and mark todos as complete:
   function markAsComplete(todo: Todo): Boolean {
        let bUpdated = false
        todos.map((td:Todo) => {
            if (td.id == todo.id){
                bUpdated = true
                td.completed = true
            }
        })
        return bUpdated
   }

   function addToDo(todo:Todo): Boolean{
        try {
            todos.push(todo)
            console.log(`Added "${todo.title}"" to list!`)
            return true
        } catch {
            console.log("Error adding to the todo object!")
            return false
        }
   }

Enter fullscreen mode Exit fullscreen mode

7. Next Steps

That's it for now, hope you enjoyed this tutorial. I will be working on some additional tutorials to dig deeper into useful TypeScript features and use cases.

  • Coming Up Next: Deep dive into TypeScript functions and advanced types.
  • Resources:
  • Challenge: Create a TypeScript interface for a blog post and use it to type-check a list of blog posts.

See you next time!

Top comments (0)