下面是一些示例代码来说明这个问题:
enum ServicePlugin {
Plugin1,
Plugin2,
Plugin3,
}
interface PluginOptions {
[ServicePlugin.Plugin1]: { option1: string };
[ServicePlugin.Plugin2]: { option1: number; option2: number };
}
type PluginOptionsMap = Omit<
{ [key in ServicePlugin]: undefined },
keyof PluginOptions
> &
PluginOptions;
type PluginConfig<T extends ServicePlugin> =
PluginOptionsMap[T] extends undefined
? { plugin: T }
: {
plugin: T;
options: PluginOptionsMap[T];
};
const params: PluginConfig<ServicePlugin>[] = [
{
plugin: ServicePlugin.Plugin1,
options: {
option1: "foo",
},
},
{
plugin: ServicePlugin.Plugin2,
options: {
option1: 123,
option2: 456,
},
},
{
plugin: ServicePlugin.Plugin2,
options: {
option1: "bar", // No error here even though it is the wrong options type
},
},
{
plugin: ServicePlugin.Plugin3,
// Error: 'options' is not declared here
},
];
类型PluginConfig<ServicePlugin>[]
的行为更像是所有插件的联合数组,而不是单个插件的array.这是有道理的,但这不是我想要的.
How can I create an array of generic objects where the generic type of each object is a particular enum value?个