Akbar Ahmadi Saray
← Back to blog
ENFA

Getting Started with TypeScript

typescriptjavascriptprogramming

What is TypeScript?

TypeScript is a programming language built on top of JavaScript. Its most important feature is static typing — variable types are checked at compile time rather than at runtime.

Why TypeScript?

  • Errors caught earlier — before the program runs
  • Better autocomplete in editors like VS Code
  • More readable code for larger teams
  • Safer refactoring — when you rename a function, the compiler finds every usage

Installation

npm install -D typescript
npx tsc --init

Basic Types

// Primitive types
let name: string = "Ahmadi";
let age: number = 25;
let isActive: boolean = true;

// Array
let tags: string[] = ["typescript", "javascript"];

// Object with interface
interface User {
  id: number;
  name: string;
  email?: string; // optional
}

const user: User = {
  id: 1,
  name: "Ali Ahmadi",
};

Typed Functions

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

// Arrow function
const greet = (name: string): string => {
  return `Hello, ${name}!`;
};

Union Types

Sometimes a variable can hold multiple types:

let id: string | number;

id = 123;      // valid
id = "abc-1";  // valid
id = true;     // error!

Generic Types

function getFirst<T>(arr: T[]): T {
  return arr[0];
}

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

Next Steps