【发布时间】:2021-09-17 07:35:33
【问题描述】:
为什么在 TypeScript 中不能进行以下操作?
abstract class Generic<T> {
// ...
}
class Specific1 extends Generic<string> {
// ...
}
class Specific2 extends Generic<number> {
// ...
}
// this is where stuff goes wrong, compiler wants me to provide generic type arguments
// |
// ˅
abstract class Wrapper<T extends Generic> {
// ...
}
class Wrapper1 extends Wrapper<Specific1> {
// ...
}
class Wrapper2 extends Wrapper<Specific2> {
// ...
}
使用Wrapper 泛型类行,我想表达我只想让类进入Wrapper 作为“专门实现”Generic 的泛型类型,即Specific1 和Specific2 , 在这种情况下。
在我正在进行的项目中,Generic 的泛型类型比此处显示的要多,而且实现也更多,即更多 SpecificX 类。我可以通过将之前传递给SpecificX 的所有泛型类型传递给WrapperX 来避免这个问题,如下所示:
class Specific1 extends Generic<type1, type2, type3> {
...
}
...
class Wrapper1 extends Wrapper<type1, type2, type3> {
...
}
...但我只是觉得很脏,我想知道是否有更好的方法来解决这个问题。我已经定义了我的 SpecificX 类及其泛型类型,并希望避免在其他位置再次这样做。
简单的 DRY,但我不知道如何在 TypeScript 中做到这一点:(
【问题讨论】:
标签: typescript generics dry typescript-generics