Interface Definition
Interfaces define the shape of objects using property names and their corresponding types. They act as contracts that objects must follow to be considered compatible with the interface.
About 716 wordsAbout 9 min
2025-08-05
Note
Interfaces in TypeScript define contracts for objects, specifying the shape and structure that objects must follow. They enable strong typing for object literals, classes, and functions while supporting extension and implementation for flexible design patterns.
Interfaces provide a powerful way to define the structure of objects, ensuring type safety while maintaining JavaScript's dynamic nature.
Interface Definition
Interfaces define the shape of objects using property names and their corresponding types. They act as contracts that objects must follow to be considered compatible with the interface.
Optional Properties
Interface properties can be marked as optional using the ? suffix, allowing objects to implement interfaces without providing all properties. This is useful for configuration objects and partial data.
Readonly Properties
Properties can be marked as readonly to prevent modification after object creation. This helps enforce immutability and prevent accidental changes to important data.
Interfaces define contracts that objects must follow, enabling type checking and better code organization.
Basic Interface Definition
Interfaces define the structure that objects must follow, specifying property names and their types.
interface Student {
name: string;
assignmentMark: number;
examMark: number;
}
const student: Student = {
name: "Alice",
assignmentMark: 85,
examMark: 92
};Step 1
Optional Properties
Use the ? operator to mark properties as optional, allowing objects to implement interfaces without providing all properties.
interface User {
id: number;
name: string;
email?: string; // Optional property
phone?: string; // Optional property
}
const user1: User = { id: 1, name: "John" }; // Valid
const user2: User = { id: 2, name: "Jane", email: "jane@example.com" }; // ValidStep 2
Readonly Properties
Mark properties as readonly to prevent modification after object creation, enforcing immutability.
interface Configuration {
readonly apiUrl: string;
readonly timeout: number;
debug: boolean;
}
const config: Configuration = {
apiUrl: "https://api.example.com",
timeout: 5000,
debug: false
};
config.apiUrl = "https://new.api.com"; // Error: Cannot assign to 'apiUrl' because it is read-onlyStep 3
Interfaces support extension and class implementation, enabling hierarchical design patterns.
Interface Extension Interfaces can extend other interfaces, inheriting their properties and adding new ones.
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: string;
department: string;
}
const employee: Employee = {
name: "Bob",
age: 30,
employeeId: "EMP-001",
department: "Engineering"
};Class Implementation Classes can implement interfaces, ensuring they provide all required properties and methods.
interface Logger {
log(message: string): void;
error(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(`[INFO] ${message}`);
}
error(message: string): void {
console.error(`[ERROR] ${message}`);
}
}Multiple Interface Implementation Classes can implement multiple interfaces, combining different contracts.
interface Serializable {
serialize(): string;
}
interface Validatable {
validate(): boolean;
}
class User implements Serializable, Validatable {
constructor(
public id: number,
public name: string,
public email: string
) {}
serialize(): string {
return JSON.stringify({
id: this.id,
name: this.name,
email: this.email
});
}
validate(): boolean {
return this.name.length > 0 &&
this.email.includes('@');
}
}Interfaces can define function signatures, enabling strong typing for callback functions and higher-order functions.
interface SearchFunction {
(source: string, subString: string): boolean;
}
const mySearch: SearchFunction = function(source, subString) {
return source.search(subString) > -1;
};
// Usage with higher-order functions
interface ArrayProcessor {
<T>(array: T[], processor: (item: T) => T): T[];
}
const processArray: ArrayProcessor = <T>(array: T[], processor: (item: T) => T) => {
return array.map(processor);
};Interfaces can define index signatures for objects with dynamic property names:
interface StringDictionary {
[index: string]: string;
}
const capitals: StringDictionary = {
"USA": "Washington D.C.",
"UK": "London",
"Japan": "Tokyo"
};
// Generic index signature
interface NumericDictionary<T> {
[index: number]: T;
}
const scores: NumericDictionary<number> = {
0: 95,
1: 87,
2: 92
};A TypeScript construct that defines the shape of an object, specifying the types of its properties and methods, serving as a contract that objects must follow.
An interface property marked with the ? suffix that may or may not be present in objects implementing the interface.
An interface property marked with the readonly keyword that cannot be modified after the object is created, enforcing immutability.
A way to define types for objects with dynamic property names, allowing objects to have properties with consistent types but arbitrary names.
c50b0-feat: some nots for tson Copyright Ownership:WARREN Y.F. LONG
License under:Attribution-NonCommercial-NoDerivatives 4.0 International (CC-BY-NC-ND-4.0)