I'm porting a JavaScript project into TypeScript. However, I'm struggling to find a good design pattern for the library to be modular.
Basic Idea
My library provides a core/minimum functionality. As an example, let's say it returns the browser specs as an object like this:
{
browser:"chrome",
version:"15.0.3",
platform:"windows",
screen-width:"1200",
// .. etc
}
This library will be installed via NPM. But to get the most out of the library, a user has to install "modules" that processes the above object gives a different result.
For example, one module will give what CSS features are not supported in this version of the browser.
{
unsupportedFeatures:[
"a",
"b",
"c",
// ... etc
]
}
Another module will take the core library result AND the aforementioned module result and process the DOM to see if there's any unsupported CSS defined.
{
notWorking:[
"a",
"b",
// ... etc
]
}
Note: This is not the actual function of the library it's just an example to illustrate how modules rely on the core library result and each other's result.
What I have tried
I tried defining the core library as a function then adding modules as prototypes.
One problem with this is that there's no type definition for neither the core library nor the added prototype functions.
I've also tried defining the core library as a class, but that didn't work either, now with compiler errors.
I've also tried merging namespace interface declaration, but it results in other compile errors.
At this point, I'm out of ideas, All the above solutions are valid JavaScript but doesn't really work in TypeScript.
How can I approach this problem in TypeScript? I think it's fairly common to write librares that are modular/extensible in this way, so what it the ideal design pattern to follow? Given that it provides type saftey and auto-completion for the core library, the module author and the user.
Aucun commentaire:
Enregistrer un commentaire