I'm encountering difficulties when attempting to correctly define a method within a class. To begin with, here is the initial class structure:
export class Plugin {
configure(config: AppConfig) {}
beforeLaunch(config: AppConfig) {}
afterSetup(runtime: Runtime) {}
afterStartup(runtime: Runtime) {}
onUserError(error: UserError) {}
}
Furthermore, there is another class responsible for programmatically executing some of these methods:
export class PluginManager {
_plugins: Plugin[];
_pythonPlugins: any[];
constructor() {
this._plugins = [];
this._pythonPlugins = [];
}
private setUpPlugins = (property: keyof Plugin, parameter:AppConfig | Runtime | UserError ) => {
for (const p of this._plugins) p[property](parameter);
for (const p of this._pythonPlugins) p[property]?.(parameter);
}
The issue arises when the parameter in the initial programmatic call within setUpPlugins raises an error:
Argument of type 'AppConfig | Runtime | UserError' is not assignable to parameter of type 'AppConfig & Runtime & UserError'.
Type 'AppConfig' is not assignable to type 'AppConfig & Runtime & UserError'.
Type 'AppConfig' is missing certain properties from type 'Runtime'. (tsserver 2345)
The expectation for an intersection type rather than a union type is perplexing. I attempted addressing this using generics:
private setUpPlugins = <T extends keyof Plugin, U extends Parameters<Plugin[T]>> (property: T, parameter:U ) => {
for (const p of this._plugins) p[property](parameter);
for (const p of this._pythonPlugins) p[property]?.(parameter);
}
However, a new error has surfaced regarding the parameter:
Argument of type '[config: AppConfig] | [config: AppConfig] | [runtime: Runtime] | [runtime: Runtime] | [error: UserError]' is not assignable to parameter of type 'AppConfig & Runtime & UserError'.
Type '[config: AppConfig]' is not assignable to type 'AppConfig & Runtime & UserError'.
Type '[config: AppConfig]' is not assignable to type 'Runtime'. (tsserver 2345)
What would be the correct approach to resolving this issue without resorting to the use of 'any'?