【发布时间】:2018-11-17 23:16:54
【问题描述】:
考虑下面的类
class SomeBaseClass<T extends string | number> {
...
}
以下条件类型使用infer关键字
type ExtractInner<T> = T extends SomeBaseClass<infer U> ? U : T;
这样,我们可以像这样提取SomeBaseClass 中使用的泛型类型(这或多或少来自文档)
type InferredString = ExtractInner<SomeBaseClass<string>> // InferredString is just type string
在我稍微高级一点的场景中,情况如下
class StringVersion extends SomeBaseClass<string> {
...
}
class NumberVersion extends SomeBaseClass<number> {
...
}
如何定义一个类型ExtractInnerWithExtend 使其等价于ExtractInner?即:
type InferredStringWithExtend = ExtractInnerWithExtend<StringVersion> // InferredStringWithExtend should be string
type InferredNumberWithExtend = ExtractInnerWithExtend<NumberVersion> // InferredStringWithExtend should be number
在这种情况下使用ExtractInner 将得到简单的string | number,我实际上期望得到string 或number,而不是联合类型。这可能是一个错误吗?我正在尝试的可能吗?
非常感谢。
【问题讨论】:
标签: typescript typescript-typings typescript2.0