I am currently working on a project where I need to easily define and use new plugins using TypeScript in my IDE. My folder structure looks like this:
src
│ ...
└── plugins
└── pluginA
| index.ts
└── pluginB
| index.ts
└── ...
index.ts <-- "here I want to combine all plugins in one object"
Each plugin has a default export in index.ts
with an interface as follows:
interface Plugin {
name: string
...
}
src/plugins/pluginA/index.ts
export default {
name: "pluginA",
...
}
src/plugins/index.ts
import pluginA from "./pluginA"
import pluginB from "./pluginB"
...
export default {
[pluginA.name]: pluginA,
[pluginB.name]: pluginB,
...
}
I aim for TypeScript to be able to understand the names of existing plugins (to infer the Literal type of keys of the plugins).
This means that when using plugins in my code, I want it to look something like this:
import plugins from "src/plugins"
...
const plugin = plugins["nonExistingPlugin"] // TypeScript should show error here if no plugin exists with this name
const anotherPlugin = plugins["plug_"] // I expect the IDE to autocomplete the name of the plugin from the existing ones
// "pluginA"
// "pluginB"
// "..."
All my attempts so far have led me to TypeScript recognizing the `name` property of the plugin as a `string`, but not inferring a Literal type.
Is there a way for TypeScript to achieve this? And if not, are there any other methods to accomplish this goal?