dimanche 18 septembre 2022

How to dynamically add functions to typescript interface and its implementation?

I am working on a typescript package where users can extend its functionality by adding new features (actions) and the implementation for that feature.

//IActions.ts -----------
export interface IActions {
  doSomething1(options?: Options1): Person;
  doSomething2(): Person;
  finallyDo(): Results;
  /*package user can extend this actions in their own files
    without modifying source files.*/

}

//Person.ts -----------
export default class Person implements IActions {
  actionLog: Log[];
  constructor(config?: PersonConfig) {
    //...
  }
  
  doSomething1(options?: Options1): Person {
    //actionLog.push...
    //...
    return this;
  }

  doSomething2(): Person {
    //actionLog.push...
    //...
    return this;
  }
  
  /*package user can extend this actions with their implantation
    in their own files without modifying source files.*/

  finallyDo(): Results {
    //...
  }
}

//PersonBuilder.ts -----------
interface PersonBuilder{
  createPerson: (config?: PersonConfig) => IActions;
}

export const personBuilder: PersonBuilder = {
  createPerson: (config?: PersonConfig) => {
    return new Person(config);
  },
};

//TestPersonBuilder.ts -----------
import personBuilder from 'person-builder-package';

const person = personBuilder.createPerson({...});
const result = await person
      .doSomething1(..)
      .doSomething2(..)
      .doSomething1(..)
      //package user can call their function with Type Annotations.
      .finallyDo();
  1. looking for a clean way to add new features (actions), something like 'Extension' method in c# but with ability to mock/test interface implementation.
  2. any similar design pattern that i can look into.
  3. user can build their own packages like plugins to extend this package.

Thanks.

Aucun commentaire:

Enregistrer un commentaire