TypeScript Essentials

TypeScript Basics for Angular

Learn the TypeScript fundamentals you need for Angular development — variables, functions, type annotations, and modern JavaScript features.

Why TypeScript?

Angular is built with TypeScript and requires it for development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds:

  • Static type checking — catch errors at compile time
  • Better IDE support — autocomplete, refactoring, navigation
  • Modern features — decorators, generics, enums
  • Self-documenting code — types serve as documentation

Variables and Type Annotations

Basic Types

typescript
// Explicit types
let name: string = 'Angular';
let version: number = 19;
let isStable: boolean = true;
let features: string[] = ['Components', 'Services', 'Routing'];

// Type inference (TypeScript figures it out)
let framework = 'Angular';   // inferred as string
let count = 42;               // inferred as number

Common Types

TypeDescriptionExample
stringText values'hello', "world"
numberNumeric values42, 3.14
booleanTrue/falsetrue, false
string[]Array of strings['a', 'b']
anyAny type (avoid)let x: any = 5
unknownSafe unknown typelet x: unknown
voidNo return valuefunction log(): void {}
null / undefinedAbsence of valuelet x: null = null

Union Types

A variable can hold more than one type:

typescript
let id: string | number;
id = 'abc-123';  // OK
id = 42;         // OK
id = true;       // Error!

Type Aliases

Create reusable type definitions:

typescript
type Status = 'active' | 'inactive' | 'pending';
type ID = string | number;

let userStatus: Status = 'active';
let userId: ID = 123;

Functions

Typed Functions

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

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

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

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

Rest Parameters

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

console.log(sum(1, 2, 3, 4)); // 10

Objects and Type Safety

Object Types

typescript
function printUser(user: { name: string; age: number }) {
  console.log(`${user.name} is ${user.age} years old`);
}

printUser({ name: 'John', age: 30 }); // OK
printUser({ name: 'John' });           // Error: missing 'age'

Optional Properties

typescript
type User = {
  name: string;
  email: string;
  phone?: string;  // optional
};

const user: User = {
  name: 'Jane',
  email: 'jane@example.com',
  // phone is optional, so this is valid
};

Enums

Enums define a set of named constants:

typescript
enum Direction {
  Up = 'UP',
  Down = 'DOWN',
  Left = 'LEFT',
  Right = 'RIGHT',
}

let move: Direction = Direction.Up;

// String enum (most common in Angular)
enum HttpStatus {
  OK = 200,
  NotFound = 404,
  ServerError = 500,
}

Destructuring and Spread

Destructuring

typescript
// Object destructuring
const { name, age } = { name: 'Alice', age: 25 };

// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first = 1, second = 2, rest = [3, 4, 5]

// Function parameter destructuring
function displayUser({ name, email }: { name: string; email: string }) {
  console.log(`${name} (${email})`);
}

Spread Operator

typescript
const defaults = { theme: 'light', lang: 'en' };
const userPrefs = { theme: 'dark' };
const settings = { ...defaults, ...userPrefs };
// { theme: 'dark', lang: 'en' }

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

Promises and Async/Await

Angular's HTTP client returns Observables, but you'll still encounter Promises:

typescript
// Promise-based
function fetchData(): Promise<string> {
  return new Promise((resolve) => {
    setTimeout(() => resolve('Data loaded'), 1000);
  });
}

// Async/Await
async function loadData() {
  const data = await fetchData();
  console.log(data); // 'Data loaded'
}

Template Literals

typescript
const name = 'Angular';
const version = 19;

// Template literal
const message = `Welcome to ${name} v${version}!`;

// Multi-line strings
const html = `
  <div>
    <h1>${name}</h1>
    <p>Version ${version}</p>
  </div>
`;

Null Safety

Optional Chaining (?.)

typescript
const user = { profile: { avatar: 'pic.jpg' } };
const avatar = user?.profile?.avatar; // 'pic.jpg'
const bio = user?.profile?.bio;       // undefined (no error)

Nullish Coalescing (??)

typescript
const input = null;
const value = input ?? 'default'; // 'default'

// Different from ||  which treats 0, '', and false as falsy
const count = 0;
console.log(count || 10);  // 10
console.log(count ?? 10);  // 0

Next Steps

With these TypeScript basics under your belt, you're ready to explore types, interfaces, and generics — the building blocks for writing type-safe Angular applications.