Typescript Guide: Everything you need to know!

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.


This content originally appeared on DEV Community and was authored by Ankita Kanchan

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

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);

Step 3: Compile and Run the Code

Compile your TypeScript file to JavaScript and run it:

npx tsc app.ts
node app.js

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";

Arrays

Arrays are easy to define and use:

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

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,
};

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

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!

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,
};

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,
};

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;
}

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");

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();

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();

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>;
};

Typing hooks is also straightforward:

const [count, setCount] = useState<number>(0);

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! 🎉


This content originally appeared on DEV Community and was authored by Ankita Kanchan


Print Share Comment Cite Upload Translate Updates
APA

Ankita Kanchan | Sciencx (2024-08-17T17:30:39+00:00) Typescript Guide: Everything you need to know!. Retrieved from https://www.scien.cx/2024/08/17/typescript-guide-everything-you-need-to-know/

MLA
" » Typescript Guide: Everything you need to know!." Ankita Kanchan | Sciencx - Saturday August 17, 2024, https://www.scien.cx/2024/08/17/typescript-guide-everything-you-need-to-know/
HARVARD
Ankita Kanchan | Sciencx Saturday August 17, 2024 » Typescript Guide: Everything you need to know!., viewed ,<https://www.scien.cx/2024/08/17/typescript-guide-everything-you-need-to-know/>
VANCOUVER
Ankita Kanchan | Sciencx - » Typescript Guide: Everything you need to know!. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/17/typescript-guide-everything-you-need-to-know/
CHICAGO
" » Typescript Guide: Everything you need to know!." Ankita Kanchan | Sciencx - Accessed . https://www.scien.cx/2024/08/17/typescript-guide-everything-you-need-to-know/
IEEE
" » Typescript Guide: Everything you need to know!." Ankita Kanchan | Sciencx [Online]. Available: https://www.scien.cx/2024/08/17/typescript-guide-everything-you-need-to-know/. [Accessed: ]
rf:citation
» Typescript Guide: Everything you need to know! | Ankita Kanchan | Sciencx | https://www.scien.cx/2024/08/17/typescript-guide-everything-you-need-to-know/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.