Using a generic type argument with `typeof T`

前端 未结 1 1050
醉话见心
醉话见心 2021-01-17 07:46

I have a factory-like function that is meant to return an sub-class instance of BaseApi. It currently looks something like this (trimmed out irrelevant parts):<

相关标签:
1条回答
  • 2021-01-17 07:55

    What you actually want is new() => T, since you intend to use the argument as a constructor and produce a T. Even if you could write typeof T, that wouldn't be what you want, since T might not have a zero-argument constructor.

    Remember that the typeof operator takes a value and produces a value. T is already a type; it is not a value.

    Naturally, this is addressed in the TypeScript FAQ https://github.com/Microsoft/TypeScript/wiki/FAQ#why-cant-i-write-typeof-t-new-t-or-instanceof-t-in-my-generic-function

    0 讨论(0)
提交回复
热议问题