【发布时间】:2020-11-25 07:47:55
【问题描述】:
我正在尝试缩小枚举值并根据枚举值返回一个不同的类实例。
为什么不使用泛型时 switch case 可以工作?
在示例 1 中,我试图缩小扩展枚举的泛型类型。但是,当我使用 switch case 时,它仍然会出错。
在示例 2 中,直接缩小枚举类型不会导致错误。
这背后有什么原因吗?
class ReportA {
constructor(public type: ReportType.A) { }
}
class ReportB {
constructor(public type: ReportType.B) { }
}
enum ReportType {
A = "A",
B = "B"
}
/** Example 1. Does not work... Why? */
class ReportFactory<Type extends ReportType> {
constructor(public type: Type) { }
public create = () => {
switch (this.type) {
case ReportType.A: {
/** ERROR! */
return new ReportA(this.type)
}
case ReportType.B: {
/** ERROR! */
return new ReportB(this.type)
}
default: throw new Error()
}
}
}
/** Example 2. Works */
class ReportFactory2 {
constructor(public type: ReportType) { }
public create = () => {
switch (this.type) {
case ReportType.A: {
/** WORKS! */
return new ReportA(this.type)
}
case ReportType.B: {
/** WORKS! */
return new ReportB(this.type)
}
default: throw new Error()
}
}
}
【问题讨论】:
-
FWIW,如果
ReportFactory2也是class会更清楚,所以 only 区别是通用参数,如下所示:pastebin.com/iPYXqCF7 实际问题,不过,我不明白为什么 TypeScript 不允许这样做 - 可能与extends但...您当然可以只使用文字值(case ReportType.A: { /** Works now */ return new ReportA(ReportType.A) }),但案例之间的重复标签和论点令人恼火,并且(在我看来)是维护问题...:-| -
@T.J.Crowder 感谢您的建议。我已经用它编辑了我的示例。
标签: typescript