Found this article, that explains how to split a class in TypeScript, however, the code seem to be in the same file
// the original class
class Employee {
doWork: void {
}
}
// extend it
interface Employee {
goToLunch(): void;
}
Employee.prototype.goToLunch = function(){
}
could somone give an example on how to extend/split a typescript class in multiple files?
I use Angular in my project.
Move the interface and class into it's own files and add the export modifier for the interface. When using the interface in the class file you will need to import it (your IDE of choice will most likely suggest it already). On the class itself you can then use the implements keyword to use the interface.
This way of using interfaces and separated files will work for Angular and regular Typescript
// Employee.interface.ts
export interface IEmployee {
goToLunch(): void;
}
// Employee.model.ts
import { IEmployee } from "./employee.interface";
class Employee implements IEmployee {
goToLunch(): void {
// Implement goToLunch logic here
}
}
If you have a class that you want to extend from the syntax is very similar to using a interface. And can also be done from different files
// WorkEmployee.model.ts
export class WorkEmployee {
goToWork(): void {
// Implement goToWork logic here
}
}
// Employee.model.ts
import { IEmployee } from "./employee.interface";
import { WorkEmployee } from "./work-employee.model";
class Employee extends WorkEmployee implements IEmployee {
goToLunch(): void {
throw new Error("Method not implemented.");
}
}
This employee will then have both logic from itself (goToLunch) and the extended class (goToWork)