TypeScript for Beginners: Why You Should Switch from JavaScript in 2026
Tutorials

TypeScript for Beginners: Why You Should Switch from JavaScript in 2026

14 min read
23 Views
Share:

What is TypeScript and why does it matter?

TypeScript is a superset of JavaScript created by Microsoft that adds static type checking to the language. Every valid JavaScript file is already valid TypeScript, but TypeScript lets you add type annotations that catch errors at compile time rather than at runtime. Think of it as JavaScript with guardrails.

In 2026, TypeScript is no longer optional for professional development. Over 78% of JavaScript developers now use TypeScript, and major frameworks like Angular, Next.js, and SvelteKit are built with TypeScript first. Job listings increasingly require TypeScript skills, and open source projects are migrating to it at an accelerating pace.

The core value proposition is simple: TypeScript catches bugs that JavaScript lets through. A typo in a property name, a function called with wrong arguments, an undefined value passed where a string was expected. These are the bugs that waste hours of debugging time, and TypeScript eliminates them before your code even runs.

Setting up TypeScript

Getting started with TypeScript requires Node.js installed on your machine. From there, installation is straightforward.

# Install TypeScript globally
npm install -g typescript

# Check version
tsc --version

# Initialize a TypeScript project
mkdir my-ts-project && cd my-ts-project
npm init -y
npm install -D typescript
npx tsc --init

The tsc --init command creates a tsconfig.json file with default settings. For beginners, these defaults work well. The most important settings to understand are target (which JavaScript version to compile to), strict (enables all strict type checking), and outDir (where compiled JavaScript files go).

// tsconfig.json - recommended starter config
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "strict": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"]
}

Basic types

TypeScript provides several primitive types that map directly to JavaScript values.

// Primitive types
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;

// Arrays
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];

// Alternative array syntax
let scores: Array<number> = [95, 87, 72];

// Tuples - fixed-length arrays with specific types
let coordinates: [number, number] = [40.7128, -74.0060];
let userEntry: [string, number] = ["Alice", 30];

Type inference

TypeScript is smart enough to infer types in most cases, so you do not need to annotate everything explicitly.

// TypeScript infers these types automatically
let message = "Hello"; // string
let count = 42;        // number
let items = [1, 2, 3]; // number[]

// You only need explicit types when TypeScript cannot infer
let data: string | number; // could be either
data = "hello";
data = 42;

Functions

Function type annotations specify the types of parameters and the return type.

// Basic function with types
function add(a: number, b: number): number {
  return a + b;
}

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

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

// Default parameters
function createUser(name: string, role: string = "viewer"): object {
  return { name, role };
}

// Rest parameters
function sum(...numbers: number[]): number {
  return numbers.reduce((total, n) => total + n, 0);
}

Interfaces and type aliases

Interfaces and type aliases let you define custom types for objects, which is where TypeScript really shines.

// Interface - defines the shape of an object
interface User {
  id: number;
  name: string;
  email: string;
  isAdmin?: boolean; // optional property
  readonly createdAt: Date; // cannot be modified after creation
}

// Using the interface
function getUser(id: number): User {
  return {
    id,
    name: "Alice",
    email: "alice@example.com",
    createdAt: new Date()
  };
}

// Type alias - similar to interface but more flexible
type Status = "active" | "inactive" | "suspended";
type ApiResponse<T> = {
  data: T;
  status: number;
  message: string;
};

// Extending interfaces
interface AdminUser extends User {
  permissions: string[];
  department: string;
}

Union and intersection types

Union types allow a value to be one of several types. Intersection types combine multiple types into one.

// Union type - value can be string OR number
type ID = string | number;

function findUser(id: ID): User | null {
  // TypeScript knows id could be string or number
  if (typeof id === "string") {
    // Here TypeScript narrows the type to string
    return findBySlug(id);
  }
  return findById(id); // Here it is number
}

// Literal union types - great for status fields
type Theme = "light" | "dark" | "system";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

// Intersection type - combines types
type WithTimestamps = {
  createdAt: Date;
  updatedAt: Date;
};

type Post = {
  title: string;
  content: string;
} & WithTimestamps;

Generics

Generics let you write reusable code that works with multiple types while maintaining type safety.

// Generic function
function getFirst<T>(items: T[]): T | undefined {
  return items[0];
}

const firstNumber = getFirst([1, 2, 3]);     // number | undefined
const firstString = getFirst(["a", "b"]);    // string | undefined

// Generic interface
interface ApiResponse<T> {
  data: T;
  status: number;
  timestamp: Date;
}

const userResponse: ApiResponse<User> = {
  data: { id: 1, name: "Alice", email: "a@b.com", createdAt: new Date() },
  status: 200,
  timestamp: new Date()
};

// Generic with constraints
interface HasId {
  id: number;
}

function findById<T extends HasId>(items: T[], id: number): T | undefined {
  return items.find(item => item.id === id);
}

Practical examples

Typing an API fetch

interface Post {
  id: number;
  title: string;
  body: string;
  userId: number;
}

async function fetchPosts(): Promise<Post[]> {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts");
  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }
  return response.json() as Promise<Post[]>;
}

// Now TypeScript knows exactly what fetchPosts returns
const posts = await fetchPosts();
console.log(posts[0].title); // TypeScript autocompletes .title

Typing React components

interface ButtonProps {
  label: string;
  onClick: () => void;
  variant?: "primary" | "secondary" | "danger";
  disabled?: boolean;
}

const Button: React.FC<ButtonProps> = ({ label, onClick, variant = "primary", disabled = false }) => {
  return (
    <button
      className={`btn btn-${variant}`}
      disabled={disabled}
    >
      {label}
    </button>
  );
};

Common mistakes and how to avoid them

The most common mistake beginners make is overusing any. When you type something as any, you disable all type checking for that value, defeating the purpose of TypeScript. If you truly do not know the type, use unknown instead, which forces you to check the type before using the value.

Another mistake is fighting the type system instead of working with it. If you find yourself adding lots of type assertions (as SomeType) or non-null assertions (!), your types probably do not accurately represent your data. Fix the types instead of overriding the compiler.

Conclusion

TypeScript is an investment that pays dividends immediately. The initial learning curve is gentle since you already know JavaScript, and the benefits of catching bugs at compile time, better IDE autocomplete, and self-documenting code make it worth every minute spent learning. Start by adding TypeScript to a small project, enable strict mode from the beginning, and let the compiler guide you toward better code.

J
Written by
Jesús García

Apasionado por la tecnologia y las finanzas personales. Escribo sobre innovacion, inteligencia artificial, inversiones y estrategias para mejorar tu economia. Mi objetivo es hacer que temas complejos sean accesibles para todos.

Share post:

Related posts

Comments

Leave a comment

Recommended Tools

The ones we use in our projects

Affiliate links. No extra cost to you.

Need technology services?

We offer comprehensive web development, mobile apps, consulting, and more.

Web Development Mobile Apps Consulting