- Basic Object Shape
- Optional Properties
- Readonly Properties
- Index Signatures
- Extending Interfaces
- Function Types
- Hybrid Types
- Class Types
- Intersection Types
- Implementing Interfaces in Classes
- Types Vs Interfaces
Defines the shape of an object, specifying the properties and their types.
interface OfficeEmployee {
name: string;
position: string;
}
const michaelScott: OfficeEmployee = {
name: "Michael Scott",
position: "Regional Manager"
};Allows properties to be optional by adding a question mark ?.
interface OfficeEmployee {
name: string;
position?: string;
}
const jimHalpert: OfficeEmployee = {
name: "Jim Halpert"
};Ensures properties cannot be changed after initialization.
interface DundieAward {
readonly id: number;
title: string;
}
const bestBossAward: DundieAward = {
id: 1,
title: "Best Boss"
};
// bestBossAward.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.Defines properties with dynamic keys and their types.
interface ScrantonBranch {
[employeeName: string]: string;
}
const scrantonEmployees: ScrantonBranch = {
"Michael Scott": "Regional Manager",
"Dwight Schrute": "Assistant Regional Manager"
};Allows interfaces to inherit properties from other interfaces.
interface Employee {
name: string;
}
interface Salesperson extends Employee {
salesRegion: string;
}
const phyllisVance: Salesperson = {
name: "Phyllis Vance",
salesRegion: "Northeast"
};Describes the types for functions, including parameters and return types.
interface MeetingScheduler {
(time: string, topic: string): string;
}
const scheduleMeeting: MeetingScheduler = (time: string, topic: string) => {
return `Meeting scheduled at ${time} about ${topic}`;
};Interfaces can describe objects that are both functions and have properties.
interface Prank {
(target: string): string;
prankName: string;
execute(): void;
}
const jimPrank: Prank = (target: string) => {
return `Pranking ${target}`;
};
jimPrank.prankName = "Stapler in Jello";
jimPrank.execute = () => {
console.log("Executing prank: Stapler in Jello");
};Defines the shape of an instance of a class.
interface Manager {
department: string;
manage(): void;
}
class OfficeManager implements Manager {
department: string;
constructor(department: string) {
this.department = department;
}
manage() {
console.log(`Managing the ${this.department} department`);
}
}Combines multiple types into one.
interface Event {
title: string;
date: string;
}
interface Party {
theme: string;
}
type OfficeParty = Event & Party;
const dundieAwards: OfficeParty = {
title: "Dundie Awards",
date: "Friday, 7 PM",
theme: "Awards Night"
};Implements an interface in a class to ensure the class adheres to the interface structure.
interface Volunteer {
name: string;
task(): void;
}
class OfficeVolunteer implements Volunteer {
name: string;
constructor(name: string) {
this.name = name;
}
task() {
console.log(`${this.name} is organizing the charity event`);
}
}
const pamBeesly = new OfficeVolunteer("Pam Beesly");
pamBeesly.task(); // Pam Beesly is organizing the charity eventTypes and interfaces in TypeScript serve different purposes and have distinct use cases. Interfaces are primarily used to define the shape of objects or classes and support declaration merging, making them ideal for object-oriented programming and extending third-party libraries. Types, on the other hand, are more versatile, capable of representing primitives, unions, intersections, and complex type constructions. They are suitable for creating complex types, utility types, and working with a broader range of type definitions. Use interfaces for defining object structures and when declaration merging is needed, and use types for complex type definitions, working with primitives, and creating utility types.
-
Object Shape Definition:
- Use interfaces when defining the structure of an object or a class. Interfaces are specifically designed for this purpose and are more readable and conventional in the context of object-oriented programming.
-
Declaration Merging:
- Interfaces can be merged, meaning you can declare the same interface multiple times, and TypeScript will combine them into a single interface definition. This is useful for extending the capabilities of third-party libraries or organizing your code.
-
Complex Type Definitions:
- Use types when you need to define more complex types that go beyond the shape of an object. This includes union types, intersection types, and tuples.
-
Working with Primitives and Non-Object Types:
- Types are more versatile than interfaces as they can represent any kind of type, including primitives (string, number, boolean), unions, and intersections. This makes them suitable for a broader range of type definitions.
-
Utility Types and Mapped Types:
- Use types when working with utility types or mapped types to transform existing types into new ones.
This Gist was created with the assistance of ChatGPT.