TypeScript
Beginner
1 min read
Interface Inheritance and Extension
Example
// Base interface
interface Animal {
name: string;
age: number;
}
// Single inheritance
interface Pet extends Animal {
owner: string;
}
// Multiple inheritance
interface ServiceAnimal extends Pet {
certification: string;
tasks: string[];
}
const guide: ServiceAnimal = {
name: "Rex",
age: 4,
owner: "Maria",
certification: "Guide-2023",
tasks: ["navigation", "obstacle detection"],
};
// Declaration merging — augment an existing interface
interface Window {
myAppVersion: string;
}
// Now Window has the extra property (useful for global augmentation)
// Extending to narrow an optional property to required
interface PartialUser {
id: number;
name?: string;
}
interface CompleteUser extends PartialUser {
name: string; // narrows optional to required
}
const u: CompleteUser = { id: 1, name: "Bob" };
// Extending with generics
interface Repository<T> {
findById(id: number): Promise<T | null>;
save(entity: T): Promise<T>;
delete(id: number): Promise<void>;
}
interface UserRepository extends Repository<CompleteUser> {
findByEmail(email: string): Promise<CompleteUser | null>;
}
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript