Getting Started with TypeScript Basics

A beginner-friendly introduction to TypeScript covering basic concepts, syntax, and common errors.

TypeScript is a superset of JavaScript that adds static types to your code. This helps catch errors early and makes your code easier to understand and maintain. In this tutorial, you'll learn the basics of TypeScript and how to write simple typed programs.

Let’s start by declaring variables with explicit types. TypeScript uses a colon (:) followed by the type to declare the type of a variable. Common types include string, number, and boolean. You can also create functions with typed parameters and return values.

typescript
let username: string = 'Alice';
let age: number = 30;
let isAdmin: boolean = true;

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

console.log(greet(username));

This code shows variables with specific types and a function that accepts and returns a string. TypeScript ensures you can’t assign values with incompatible types. For example, if you try to assign a number to a string variable, TypeScript will give an error.

Common TypeScript error example: If you write `let title: string = 123;`, TypeScript shows an error: "Type 'number' is not assignable to type 'string'." This means that you tried to assign a number to a variable that expects a string. To fix it, change the value to a string like "123" or update the variable type to number if needed.

Starting with these basic types and error explanations, you can write safer JavaScript code with TypeScript. As you practice, you’ll explore more advanced features like interfaces, enums, and generics to build robust applications.