首页 > 解决方案 > 泛型的窄容器由泛型

问题描述

如果我有一个像这样的通用容器

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)

这里是游乐场

标签: typescripttypescript-generics

解决方案


推荐阅读