I've been developing a "manager" class that allows for the integration of "plugins". Each plugin has the ability to enhance the data
property of the manager class.
// manager.ts
interface Data {
// some props
}
class Manager {
data: Data;
// TSC Problem: "Property 'data' has no initializer and is not definitely assigned in the constructor."
constructor() {
// It's not possible to set all potential properties of this.data because
// the Manager class is unaware of all possible plugins that may be added
}
}
Plugins receive a reference to the manager instance they are being plugged into. They can also enhance the Data
interface to better define the data object?
// plugins/A.ts
interface Data {
// additional props
}
function A(boss: Manager) {
// "A" adds unique data to boss.data specific to "A"
}
These are the questions that come to mind:
- Is this a sound design pattern?
- Is this the best way to achieve this, or are there alternative solutions?
I came across information on Declaration Merging (https://www.typescriptlang.org/docs/handbook/declaration-merging.html), which seems like the most suitable option due to the number of independent plugins involved. Discriminated Unions (https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types) might not be feasible in this scenario.
EDIT: To clarify my query; Can declaration merging be used across multiple files?