我有一个将类作为输入的函数,该函数的返回类型由类确定。在这里,到目前为止,我希望res
的类型为number
。甚至有可能
abstract class Command<R> {}
abstract class CommandHandler<R, C extends Command<R>> {
abstract execute(cmd: C): R
}
class GetNumberCommand extends Command<number> {}
class GetNumberCommandHandler extends CommandHandler<number, GetNumberCommand> {
execute(cmd: GetNumberCommand) {
return 1
}
}
function mediator<C extends Command<R>, R>(cmd: C): R {
// [ts] Type 'GetNumberCommandHandler' is not assignable to type 'CommandHandler<R, C>'.
const handler: CommandHandler<R, C> = new GetNumberCommandHandler()
return handler.execute(cmd)
}
// res should be of type number, it's `{}`
const res = mediator(new GetNumberCommand())