首页 > 解决方案 > 使用鉴别器字段创建联合类型的值

问题描述

我的问题最好用一个例子来说明:

interface A { tpe: 'a' }
interface B { tpe: 'b' }
type AB = A | B

const abMaker = (ab: AB): AB => {
  return { tpe: ab.tpe }
}

这里的return语句有如下错误:

  Type '{ tpe: "a" | "b"; }' is not assignable to type 'B'.
    Types of property 'tpe' are incompatible.
      Type '"a" | "b"' is not assignable to type '"b"'.
        Type '"a"' is not assignable to type '"b"'.

编译器无法推断返回的值是有效AB的,因为 type 的值对任何一个或单个"a" | "b"都无效。 AB

我可以通过“类型检查”的值来使其工作tpe

const abMaker = (ab: AB): AB => {
  switch (ab.tpe) {
    case 'a': return { tpe: ab.tpe }
    case 'b': return { tpe: ab.tpe }
  }
}

有一个更好的方法吗?

标签: typescripttypes

解决方案


推荐阅读