TS TypeScript
Interfaces & Classes
As your programs grow, you need ways to describe the shape of your data and organize code into reusable structures. Interfaces and classes are TypeScript's primary tools for this.
Interfaces
An interface defines the shape of an object — what properties it should have and what types those properties should be:
interface User {
name: string;
email: string;
age: number;
}
const alice: User = {
name: "Alice",
email: "[email protected]",
age: 30,
};
Optional & readonly properties
interface User {
name: string; // required
email: string; // required
age?: number; // optional — the ? makes it optional
readonly id: number; // readonly — cannot be changed after creation
}
const user: User = {
name: "Alice",
email: "[email protected]",
id: 1,
};
user.age = 30; // ✅ Optional — can be set
user.id = 2; // ❌ Error: Cannot assign to 'id' because it is read-only
Interfaces vs type aliases
Both interface and type can define object shapes. The main difference:
- → Interfaces can be extended and merged — great for large, evolving systems.
- → Type aliases are more flexible — they can represent unions, primitives, and tuples.
- → In practice, use interfaces for object shapes and types for everything else.
Classes
Classes combine data (properties) and behavior (methods) into a single structure. TypeScript adds access modifiers and interface implementation:
class Student implements User {
name: string;
email: string;
private gpa: number;
constructor(name: string, email: string, gpa: number) {
this.name = name;
this.email = email;
this.gpa = gpa;
}
// Method
getSummary(): string {
return `${this.name} (${this.email}) — GPA: ${this.gpa}`;
}
}
const s = new Student("Alice", "[email protected]", 3.8);
console.log(s.getSummary());
Access modifiers
- → public — accessible from anywhere (default).
- → private — accessible only within the class.
- → protected — accessible within the class and its subclasses.
Editor
TypeScript
Console
Quiz
What keyword defines an interface in TypeScript?
Challenge
Create an interface called User with name and email properties. Then create a class that implements this interface and adds a greet() method that returns a string.