从泛型类型获取函数返回类型

时间:2018-09-14 10:39:53

标签: typescript generics

我有一个将类作为输入的函数,该函数的返回类型由类确定。在这里,到目前为止,我希望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())

0 个答案:

没有答案