Angular TypeScript Basics
Angular applications use TypeScript as their main language. TypeScript is JavaScript with an extra feature called types. A type tells the computer what kind of value a variable holds, such as text, a number, or a list.
What Is TypeScript
Think of TypeScript as a spell-checker for your code. A spell-checker underlines a misspelled word before you send an email. TypeScript underlines a wrong value before you run your program. You catch mistakes early, and your application breaks less often.
Browsers cannot read TypeScript directly. A tool called the compiler converts your TypeScript files into plain JavaScript. Angular runs this compiler for you, so you never convert files by hand.
How TypeScript Reaches the Browser
+----------------+ +----------------+ +----------------+ | TypeScript | | Compiler | | JavaScript | | (.ts files) | --> | checks types | --> | runs in the | | you write | | and converts | | browser | +----------------+ +----------------+ +----------------+
Basic Types
You add a type after the variable name with a colon. The compiler then rejects any value that does not match.
let courseName: string = 'Angular';
let totalLessons: number = 29;
let isFree: boolean = true;
let topics: string[] = ['Signals', 'Routing', 'Forms'];
totalLessons = 'many'; // Error: text cannot go into a number
The last line fails because totalLessons accepts only numbers. The compiler shows the error in your editor before you open the browser.
Type Inference
TypeScript guesses the type when you assign a value right away. You can write let city = 'Delhi'; and TypeScript treats city as a string. Most Angular code relies on this guess, so you add types only where they help readers.
Interfaces
An interface works like a blueprint for an object. A house blueprint lists the rooms every house must have. An interface lists the properties every object must have.
interface Student {
id: number;
name: string;
email?: string; // the question mark makes this property optional
}
const learner: Student = { id: 1, name: 'Asha' };
Angular developers use interfaces to describe data that arrives from a server. A Student interface tells every team member which fields to expect.
Classes
A class is a template that creates objects with their own data and actions. A cookie cutter shapes many cookies from one design. A class shapes many objects from one design.
class Counter {
count: number = 0;
increase(): void {
this.count++;
}
}
const clicks = new Counter();
clicks.increase();
Every Angular component is a class. Properties hold the data, and methods hold the actions that users trigger on the page.
Functions with Types
You can add types to the inputs and the output of a function. The compiler then checks every call.
function addMarks(first: number, second: number): number {
return first + second;
}
addMarks(40, 55); // works
addMarks('40', 55); // Error: first input must be a number
Decorators
A decorator is a label that starts with the @ symbol. It sits above a class and gives Angular extra instructions. A parcel label tells the courier where to deliver the box. A decorator tells Angular how to treat the class.
@Component({
selector: 'app-welcome',
template: '<p>Welcome</p>'
})
export class WelcomeComponent {}
The @Component label turns a plain class into a component. Angular also offers @Injectable for services and @Input for data that passes between components.
Imports and Exports
Each file in TypeScript works as a separate box. The export keyword opens the box so other files can use its contents. The import keyword brings those contents into another file.
// student.ts
export interface Student { id: number; name: string; }
// app.ts
import { Student } from './student';
Union Types
A union type allows a variable to hold one of several types. Use the pipe symbol to separate the choices.
let userId: number | string;
userId = 101;
userId = 'A101';
Practice Exercise
Create a file named book.ts. Define an interface called Book with a title, a price, and an optional author. Build a class called Library that stores a list of books and has a method named addBook. Run the compiler and fix every error it reports. This exercise builds the habit of reading type errors, which you will do daily in Angular.
Key Points
- TypeScript adds types to JavaScript and catches mistakes early.
- The compiler converts TypeScript into JavaScript for the browser.
- Interfaces describe the shape of data.
- Classes create objects, and every Angular component is a class.
- Decorators label a class with instructions for Angular.
