typescript - 如何在 TypeScript 的通用类型参数中使用联合类型作为约束
问题描述
似乎不可能有一个受联合类型约束的泛型类。基本上是这样的:
class Shoe {
constructor(public size: number){}
}
class Dress {
constructor(public style: string){}
}
class Box <T extends Shoe | Dress > {
}
然后这个:
// because move can move multiple boxes of Box of shoes or Box of dress
class Move<B extends Box<Shoe>[] | Box<Dress>[]> {
private stuff: B;
constructor(public toMove: Box<Shoe>[] | Box<Dress>[]) {
this.stuff = toMove // this does not compile
}
}
或者如何实现?我有一个Playground 链接来展示这种情况
解决方案
我想,这又是对你真实意图的猜测,这应该足够了:
class Shoe {
constructor(public size: number){}
}
class Dress {
constructor(public style: string){}
}
class Box <T extends Shoe | Dress > {
}
// because move can move multiple boxes of Box of shoes or Box of dress
class Move<B extends Box<Shoe>[] | Box<Dress>[]> {
private stuff: B;
constructor(public toMove: B) {
this.stuff = toMove;
}
}
推荐阅读
- neural-network - 我想用 Numpy 模拟一个量化的 MobileNet V2 网络的推理过程,但是结果与 pytorch 实现的不同
- android - 反应原生:滚动视图刷新控制拉刷新不从顶部刷新
- c# - .NET Standard 的 AllowHtmlAttribute 替代品,因为它已被删除?
- javascript - 如何从 ReactJs 中的输入类型文件中获取音乐信息
- quasar-framework - 叶子和严格的q-treetick策略组合?
- r - 车包Anova“下标越界”
- javascript - 如何跟踪和收集特定字段的所有使用过的依赖 JavaScript
- c - 输入两个字符串a和b,请计算b在a中出现的次数
- javascript - 如何使用表格标题的弹出窗口中的按钮对表格进行排序
- ios - Xcode cocoa pods pod install Sentry 导致“找不到模块'Sentry'”