Skip to content

For typescript inspired from C# πŸŽ€ partial classes πŸŽ€, help divide functionality of a single class into 🍬 multiple classes 🍬 files

License

Notifications You must be signed in to change notification settings

mustafah/partials

Repository files navigation

Typescript Partials 🍬🍬🍬 (αlpha)

Inspired from C# partial classes for typescript, Simplified πŸŽ€ syntax that may help divide functionality of a single class into multiple 🍬🍬🍬 class files

Install

Install dependencies with npm:

npm i mustafah/partials

Import

import partial from 'partials';

Add your partial classes 🍬🍬🍬

Split class function through multiple files
@partial export class Employee {
    @partial work: EmployeeWork;
    @partial lunch: EmployeeLunch;
    start() {
        this.work.doWork();
        this.lunch.goToLunch();
    }
}
@partial export class EmployeeWork {
    @partial model: EmployeeModel;
    doWork() {
        console.log(`doWork()`);
    }
}
@partial export class EmployeeLunch {
    @partial model: EmployeeModel;
    goToLunch() {
        console.log(`goToLunch()`);
    }
}

🎁 Voila, Use your class πŸ‘

new Employee().start()
// Ouputs:
// goToWork()
// goToLunch()

🌱 Need initialization code ?
@partial export class Employee {
    @partial work: EmployeeWork;
    @partial lunch: EmployeeLunch;
    ///////////////////////////////////////////////
    // Use onInit() instead of class's constructor 
    /////////////////////////////////////////////
    onInit() {
        this.work.doWork();
        this.lunch.goToLunch();
    }
}

🌱 TwoWay communication between classes ?

If you tried the following scenario, JS Runtime will raise 🚫 Uncaught ReferenceError: Cannot access 'Employee' before initialization error and ⚠️ Circular dependency detected warning

@partial export class Employee {
    @partial work: EmployeeWork;
    name = 'Mustafah';
}
@partial export class EmployeeWork {
    @partial employee: Employee;
    doWork() {
        console.log(`${this.employee.name} doWork()`);
    }
}
🌱 Solution 1: Class name as string:
@partial export class EmployeeWork {
    @partial('Employee') employee;
    doWork() {
        console.log(`${this.employee.name} doWork()`);
    }
}
🌱 Solution 2: Class name as forward reference:
@partial export class EmployeeWork {
    @partial(() => Employee) employee;
    doWork() {
        console.log(`${this.employee.name} doWork()`);
    }
}
🌱 If you need strong typing, feel free to use interfaces:
@partial export class Employee {
    @partial work: EmployeeWork;
    name = 'Mustafah';
}
export interface IEmployee {
    name: string;
}
@partial export class EmployeeWork {
    @partial(() => Employee) employee: IEmployee;
}

About

For typescript inspired from C# πŸŽ€ partial classes πŸŽ€, help divide functionality of a single class into 🍬 multiple classes 🍬 files

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published