typescript - 泛型的窄容器由泛型
问题描述
如果我有一个像这样的通用容器
export interface A {
type: 'A',
value: string
}
export interface B {
type: 'B',
value: number
}
export interface Container<T> {
data: T
}
export type ContainerOfAB = Container<A | B>
ContainerOfAB
是否可以通过其数据对象的值来缩小 a 的类型?例如:
export interface A {
type: 'A',
value: string
}
export interface B {
type: 'B',
value: number
}
export interface Container<T> {
data: T
}
export type ContainerOfAB = Container<A | B>
export function detect(item: ContainerOfAB) {
switch(item.data.type) {
case 'A':
takesGenericA(item) // fails
break;
case 'B':
takesGenericB(item) // fails
break;
}
}
function takesGenericA(e: Container<A>) {
}
function takesGenericB(e: Container<B>) {
}
即使开关确实有效,它似乎也无法将容器的内部值缩小到足以传递给另一种方法?
此示例对缩小类型的任何一个调用都给出了以下错误
Argument of type 'ContainerOfAB' is not assignable to parameter of type 'Container<B>'.
Type 'A | B' is not assignable to type 'B'.
Type 'A' is not assignable to type 'B'.
Types of property 'type' are incompatible.
Type '"A"' is not assignable to type '"B"'.(2345)
这里是游乐场
解决方案
推荐阅读
- javascript - 如何使用正则表达式从括号中取出单词
- android - 更改 setHeaderTitle onCreateContextMenu 的颜色
- java - Runime.getRuntime().totalMemory() 和 ActivityManager.MemoryInfo()
- datetime - 使用 strptime 时出现错误消息,格式错误,即使它看起来正确。这是怎么回事?
- https - Google 负载均衡器创建与计算引擎 IP 不同的前端 IP
- jspdf - 如何从使用角度材料 7 虚拟滚动创建的表格中创建 pdf
- react-native - 世博会推送通知未显示在锁定屏幕上
- javascript - 在Angular6中向服务器发送请求时来自服务器的未经授权的错误
- asp.net-mvc - 下载 ZIP 文件并在浏览器 ASP.NET MVC 中输出 Rotativa PDF
- lora - 传输时 LORWAN PHYheader 大小?