DEV Community

Cover image for TypeScript Guide: Everything you need to know! Part -1
Ankita Kanchan
Ankita Kanchan

Posted on

TypeScript Guide: Everything you need to know! Part -1

If you've been coding in JavaScript and are curious about TypeScript, you're in the right place! This guide focuses on practical, real-world examples that you can start using in your projects right away without getting bogged down in too much theory.

What’s TypeScript, Really?

TypeScript is like JavaScript’s smarter sibling. It adds static typing to your code, which helps catch errors before they sneak into production. The best part? You can introduce it gradually – no need for a big overhaul!

Why Use TypeScript?

You might wonder if you really need to add another tool to your stack. The short answer is: Yes! TypeScript helps prevent common bugs, provides smarter code suggestions, and keeps large projects more maintainable. Plus, it’s flexible – you can start small and expand its use as needed.

Key Benefits:

  1. Catch Errors Early: TypeScript flags potential issues while you write code, reducing runtime errors.
  2. Enhanced Auto-Complete: Enjoy better autocompletion and real-time feedback, thanks to TypeScript’s understanding of your code.
  3. Scalable Codebase: As your project grows, TypeScript helps keep everything organized and consistent.

Getting Started with TypeScript

Step 1: Install TypeScript

Getting started with TypeScript is quick. Install it using npm (either globally or in your project):

npm install --save-dev typescript
Enter fullscreen mode Exit fullscreen mode

Step 2: Create Your First TypeScript File

Create a new file called app.ts (the .ts extension is for TypeScript). Here’s a simple example:

let greeting: string = "Hello, TypeScript!";
console.log(greeting);
Enter fullscreen mode Exit fullscreen mode

Step 3: Compile and Run the Code

Compile your TypeScript file to JavaScript and run it:

npx tsc app.ts
node app.js
Enter fullscreen mode Exit fullscreen mode

You should see "Hello, TypeScript!" in your console.

Types: The Basics

TypeScript introduces types that help make your code safer and easier to understand. Here’s an overview of the most common types you’ll use.

Numbers and Strings

Numbers and strings are the bread and butter of any program:

let age: number = 25;
let name: string = "John Doe";
Enter fullscreen mode Exit fullscreen mode

Arrays

Arrays are easy to define and use:

let scores: number[] = [90, 85, 88];
let names: string[] = ["Ankita", Shubham"];
Enter fullscreen mode Exit fullscreen mode

Objects

Objects are crucial in any application. Here’s how you define them with types:

let person: { name: string; age: number } = {
  name: "Ankita",
  age: 26,
};
Enter fullscreen mode Exit fullscreen mode

Functions

You can specify the types of function parameters and return values, making your functions more predictable:

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

let sum = add(10, 20);
console.log(sum); // 30
Enter fullscreen mode Exit fullscreen mode

Optional and Default Parameters

TypeScript makes it easy to handle optional parameters or set default values:

function greet(name: string = "Guest", greeting?: string): string {
  return `${greeting || "Hello"}, ${name}!`;
}

console.log(greet("Ankita")); // Hello, Ankita!
console.log(greet("John", "Hi")); // Hi, John!
Enter fullscreen mode Exit fullscreen mode

Working with Interfaces

Interfaces allow you to define the structure of objects in your application. They’re especially useful when working with complex objects.

interface User {
  name: string;
  age: number;
  isAdmin?: boolean; // Optional property
}

let user: User = {
  name: "Ankita",
  age: 26,
};
Enter fullscreen mode Exit fullscreen mode

Extending Interfaces

You can extend interfaces to build on top of existing ones. This is great when you have related entities:

interface Employee extends User {
  employeeId: number;
}

let employee: Employee = {
  name: "David",
  age: 35,
  employeeId: 1234,
};
Enter fullscreen mode Exit fullscreen mode

TypeScript in Real Life: A Mini Project

Let’s build a simple task manager to demonstrate how TypeScript works in a practical scenario.

Step 1: Define the Task Interface

First, define a structure for tasks:

interface Task {
  id: number;
  title: string;
  completed: boolean;
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Function to Add Tasks

Next, implement a function to add new tasks to your task list:

let tasks: Task[] = [];

function addTask(title: string): void {
  const newTask: Task = {
    id: tasks.length + 1,
    title,
    completed: false,
  };
  tasks.push(newTask);
}

addTask("Learn TypeScript");
addTask("Build a project");
Enter fullscreen mode Exit fullscreen mode

Step 3: List the Tasks

You’ll likely want to display your tasks. Here’s a simple way to do it:

function listTasks(): void {
  tasks.forEach((task) => {
    console.log(`${task.id}: ${task.title} [${task.completed ? "" : ""}]`);
  });
}

listTasks();
Enter fullscreen mode Exit fullscreen mode

Step 4: Mark a Task as Completed

Finally, you can add functionality to mark tasks as done:

function completeTask(id: number): void {
  const task = tasks.find((task) => task.id === id);
  if (task) {
    task.completed = true;
  }
}

completeTask(1);
listTasks();
Enter fullscreen mode Exit fullscreen mode

This mini project is a great start to seeing how TypeScript can improve the quality and readability of your code.

TypeScript in React

React and TypeScript are a match made in heaven. Here’s how you’d type props in a functional React component:

interface Props {
  title: string;
}

const Header: React.FC<Props> = ({ title }) => {
  return <h1>{title}</h1>;
};
Enter fullscreen mode Exit fullscreen mode

Typing hooks is also straightforward:

const [count, setCount] = useState<number>(0);
Enter fullscreen mode Exit fullscreen mode

Adding TypeScript to your React projects helps you avoid common bugs and makes your components more predictable.

Conclusion

TypeScript is more than just a fancy addition to JavaScript – it’s a tool that makes your code more reliable and easier to manage. Whether you’re working on small projects or large-scale applications, TypeScript can help keep your code clean, bug-free, and maintainable.

The best way to learn TypeScript is to start using it! Add it to your next project, and see how it can make your code safer and more fun to work with.

Feel free to ask questions or share your experiences with TypeScript in the comments below!

Happy coding! 🎉

Top comments (0)