TS
Programmers Picnic
AI-ML Classes by Champak Roy
Angular Foundation Lesson

JavaScript vs TypeScript: Level 0 to Infinity

Learn the difference between JavaScript and TypeScript from the beginning: variables, types, functions, objects, arrays, classes, interfaces, errors, compilation, Angular usage, and expert-level coding habits.

Start Lesson

1. Introduction

JavaScript and TypeScript are closely related. JavaScript is the main language of the browser. TypeScript is a typed version of JavaScript that helps developers catch mistakes earlier.

Simple meaning: JavaScript runs in the browser. TypeScript is written by developers and then converted into JavaScript.
TypeScript code
  ↓ compile
JavaScript code
  ↓ run
Browser / Node.js

2. Level 0 Meaning

JavaScript lets you write code quickly. TypeScript makes you write code more carefully.

JavaScript Flexible and directly runnable in browsers.
TypeScript JavaScript plus type checking.
Angular Uses TypeScript heavily for components, services, routing, and forms.

One-line Difference

JavaScript: value first, type later.
TypeScript: type known before running.

3. Main Difference Between JavaScript and TypeScript

Point JavaScript TypeScript
Type system Dynamic typing. Static type checking.
Runs directly in browser Yes. No. It is converted to JavaScript first.
Error detection Many errors appear while running. Many errors appear while writing or compiling.
Learning curve Easier at first. Stricter at first, safer later.
Large projects Can become hard to maintain. Better for large and team projects.
Angular usage Not the normal Angular development language. Main language used in Angular projects.

4. Why TypeScript Exists

JavaScript is powerful, but because it is very flexible, mistakes can hide until the program runs. TypeScript adds type checking so many mistakes are found earlier.

JavaScript Example

let marks = 90;

marks = "ninety";

console.log(marks);

JavaScript allows this. The variable first had a number, then a string.

TypeScript Example

let marks: number = 90;

marks = "ninety";
TypeScript will report an error because marks was declared as a number.

5. Execution Flow

JavaScript and TypeScript follow different paths before running.

JavaScript vs TypeScript Flow JavaScript .js file Browser runs directly TypeScript .ts file Compiler checks and converts JavaScript runs in browser

6. Variables: JavaScript vs TypeScript

JavaScript

let course = "Angular";
let duration = 30;
let isActive = true;

TypeScript

let course: string = "Angular";
let duration: number = 30;
let isActive: boolean = true;
TypeScript can often infer the type automatically, but writing types makes the intention clearer for beginners.

Type Inference

let course = "Angular";

// TypeScript understands:
// course is a string

7. Basic Types in TypeScript

TypeScript gives names to the kind of data a variable can hold.

Type Meaning Example
string Text data. let name: string = "Champak";
number Numbers. let marks: number = 95;
boolean True or false. let passed: boolean = true;
string[] Array of strings. let topics: string[] = ["JS", "TS"];
any Any type. Avoid when possible. let data: any = 10;
unknown Unknown type. Safer than any. let value: unknown = "hello";
void No return value. function log(): void {}

8. Functions

JavaScript Function

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

console.log(add(10, 20));
console.log(add("10", 20));

JavaScript allows both calls. The second call may create unexpected output.

TypeScript Function

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

console.log(add(10, 20));
console.log(add("10", 20));
TypeScript will report an error for add("10", 20) because the first argument should be a number.

Angular Style Method

loadCourse(id: number): void {
  console.log("Loading course", id);
}

9. Objects

JavaScript Object

const student = {
  name: "Riya",
  marks: 92
};

student.marks = "excellent";

JavaScript allows this unless the code logic prevents it.

TypeScript Object

const student: {
  name: string;
  marks: number;
} = {
  name: "Riya",
  marks: 92
};

student.marks = "excellent";
TypeScript reports an error because marks should be a number.

10. Arrays

JavaScript Array

let marks = [90, 85, 77];

marks.push("absent");

TypeScript Array

let marks: number[] = [90, 85, 77];

marks.push("absent");
TypeScript reports an error because marks is an array of numbers.

Array of Objects

let courses: { id: number; title: string }[] = [
  { id: 1, title: "Angular Basics" },
  { id: 2, title: "Angular Routing" }
];

11. Union Types

Sometimes a value can be one of several types. TypeScript supports this using union types.

let studentId: number | string;

studentId = 101;
studentId = "STU-101";

Status Example

let status: "draft" | "published" | "archived";

status = "draft";
status = "published";
status = "deleted";
TypeScript reports an error for "deleted" because it is not allowed in the union.

12. Interfaces

Interfaces define the shape of an object. They are extremely useful in Angular apps.

Without Interface

const course: { id: number; title: string; price: number } = {
  id: 1,
  title: "Angular Routing",
  price: 499
};

With Interface

interface Course {
  id: number;
  title: string;
  price: number;
}

const course: Course = {
  id: 1,
  title: "Angular Routing",
  price: 499
};

Angular Service Example

interface Course {
  id: number;
  title: string;
  level: "beginner" | "intermediate" | "advanced";
}

getCourses(): Course[] {
  return [
    { id: 1, title: "Angular Basics", level: "beginner" },
    { id: 2, title: "Angular Routing", level: "intermediate" }
  ];
}

13. Classes

JavaScript has classes, but TypeScript makes classes clearer with typed properties and methods.

JavaScript Class

class Student {
  constructor(name, marks) {
    this.name = name;
    this.marks = marks;
  }

  showResult() {
    return this.name + " scored " + this.marks;
  }
}

TypeScript Class

class Student {
  name: string;
  marks: number;

  constructor(name: string, marks: number) {
    this.name = name;
    this.marks = marks;
  }

  showResult(): string {
    return `${this.name} scored ${this.marks}`;
  }
}

Shorter TypeScript Constructor

class Student {
  constructor(
    public name: string,
    public marks: number
  ) {}

  showResult(): string {
    return `${this.name} scored ${this.marks}`;
  }
}

14. Error Detection

One of TypeScript’s biggest benefits is early error detection.

JavaScript Error Appears at Runtime

function printTitle(course) {
  console.log(course.title.toUpperCase());
}

printTitle({ name: "Angular" });

JavaScript may fail while running because title does not exist.

TypeScript Error Appears Earlier

interface Course {
  title: string;
}

function printTitle(course: Course): void {
  console.log(course.title.toUpperCase());
}

printTitle({ name: "Angular" });
TypeScript warns before running because the object does not match the Course interface.

15. Compilation

TypeScript must be compiled to JavaScript.

Install TypeScript

npm install -g typescript

Compile a TypeScript File

tsc app.ts

This creates:

app.js

Angular Compilation

ng build
In Angular, you do not normally run tsc manually. Angular CLI handles TypeScript compilation during build.

16. Why Angular Uses TypeScript

Angular projects use TypeScript because Angular apps usually have many components, services, forms, routes, APIs, models, and shared data. TypeScript makes these easier to manage.

Components Typed properties and methods make component code safer.
Services API responses can be shaped with interfaces.
Routing Route configuration uses typed structures.

Angular Component Example

import { Component } from '@angular/core';

interface Course {
  id: number;
  title: string;
  level: string;
}

@Component({
  selector: 'app-courses',
  templateUrl: './courses.html',
  styleUrl: './courses.css'
})
export class Courses {
  courses: Course[] = [
    { id: 1, title: "Angular Basics", level: "Beginner" },
    { id: 2, title: "Routing in Angular", level: "Intermediate" }
  ];

  selectCourse(course: Course): void {
    console.log(course.title);
  }
}

Angular Template

<h2>Courses</h2>

@for (course of courses; track course.id) {
  <article>
    <h3>{{ course.title }}</h3>
    <p>{{ course.level }}</p>
    <button (click)="selectCourse(course)">Select</button>
  </article>
}

17. Moving from JavaScript to TypeScript

To move from JavaScript to TypeScript, do not try to learn everything at once. Add types step by step.

Step 1: JavaScript

function calculateTotal(price, quantity) {
  return price * quantity;
}

Step 2: Add Parameter Types

function calculateTotal(price: number, quantity: number) {
  return price * quantity;
}

Step 3: Add Return Type

function calculateTotal(price: number, quantity: number): number {
  return price * quantity;
}

Step 4: Use Interface for Objects

interface CartItem {
  price: number;
  quantity: number;
}

function calculateTotal(item: CartItem): number {
  return item.price * item.quantity;
}

18. Expert-Level Differences

At expert level, TypeScript is not only about adding : string or : number. It is about designing safer systems.

Feature Why It Matters Example
Interfaces Define object shapes. interface User { id: number; name: string; }
Generics Reusable typed logic. function wrap<T>(value: T): T[]
Union types Allow controlled alternatives. "draft" | "published"
Literal types Restrict values exactly. role: "admin" | "student"
Optional properties Some fields may be missing. phone?: string
Readonly Prevent accidental changes. readonly id: number

Generic Example

function firstItem<T>(items: T[]): T {
  return items[0];
}

const firstNumber = firstItem<number>([10, 20, 30]);
const firstName = firstItem<string>(["Angular", "TypeScript"]);

API Response Generic

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message: string;
}

interface Course {
  id: number;
  title: string;
}

const response: ApiResponse<Course[]> = {
  success: true,
  data: [
    { id: 1, title: "Angular Basics" }
  ],
  message: "Courses loaded"
};

19. Common Mistakes

Mistake Problem Better Habit
Using any everywhere Removes TypeScript safety. Use proper types or unknown.
Not typing function parameters Mistakes can enter functions. Add parameter and return types.
Huge object types repeated everywhere Code becomes messy. Use interfaces.
Ignoring TypeScript errors Build may fail later. Fix errors early.
Thinking TypeScript runs directly in browser Incorrect mental model. Remember TS compiles to JS.
Using TypeScript without understanding JavaScript Concepts become confusing. Learn JavaScript fundamentals first.

20. Student Assignment

Convert the following JavaScript code into TypeScript.

JavaScript Code

const students = [
  { id: 1, name: "Amit", marks: 88 },
  { id: 2, name: "Riya", marks: 94 },
  { id: 3, name: "John", marks: 76 }
];

function getTopStudents(students, minimumMarks) {
  return students.filter(student => student.marks >= minimumMarks);
}

console.log(getTopStudents(students, 80));

Expected TypeScript Direction

interface Student {
  id: number;
  name: string;
  marks: number;
}

const students: Student[] = [
  { id: 1, name: "Amit", marks: 88 },
  { id: 2, name: "Riya", marks: 94 },
  { id: 3, name: "John", marks: 76 }
];

function getTopStudents(
  students: Student[],
  minimumMarks: number
): Student[] {
  return students.filter(student => student.marks >= minimumMarks);
}

console.log(getTopStudents(students, 80));
Final learning: JavaScript gives flexibility. TypeScript gives structure, safety, and confidence. Angular uses TypeScript because large apps need structure.

Final Summary

Question Answer
What is JavaScript? A programming language that runs directly in browsers and Node.js.
What is TypeScript? JavaScript with static type checking.
Does TypeScript run directly in browser? No. It is compiled to JavaScript first.
Why use TypeScript? To catch mistakes early and make large projects easier to maintain.
Why does Angular use TypeScript? Because Angular apps need typed components, services, routes, forms, and API models.
What should beginners avoid? Using any everywhere.
What is the best learning path? JavaScript basics first, then TypeScript types, then Angular TypeScript patterns.