PAYATHON 2026

TypeScript 中如何满足两个互斥条件组成的联合类型?

数据小陈

结论

不必先把 b 和 c 组装成一个 b: boolean、c: number | undefined 的对象再统一 return。按 bAsString 分支返回最稳妥:true 分支返回 b: true 且 c: number 的对象,false 分支返回 b: false 且 c: undefined 的对象。这样 TypeScript 会把每个返回值对应到判别联合的成员,不用写 type predicate,也不用 as CombinedType 硬断言。

为什么会报错

CombinedType 是 BaseTypeTrue | BaseTypeFalse。它要求返回值满足其中一种:b: true 且 c: number,或者 b: false 且 c: undefined。原代码里:

const b = bAsString === 'true'; // boolean
const c = cAsString === '' ? parseInt(cAsString, 10) : undefined; // number | undefined
return { a, b, c };

b 的类型是 boolean,不是字面量 true 或 false;c 的类型是 number | undefined。TypeScript 只检查对象字面量本身的结构,不会因为 b 是 true 就推断 c 一定是 number。所以 { a, b, c } 不能赋给 BaseTypeTrue | BaseTypeFalse,报错里还会提示 boolean 不能赋给 false。

推荐写法

按判别字段 b 分别返回,并确保每个分支里 c 的类型正确:

interface BaseType {
  a: string;
}

interface BaseTypeTrue extends BaseType {
  b: true;
  c: number;
}

interface BaseTypeFalse extends BaseType {
  b: false;
  c: undefined;
}

type CombinedType = BaseTypeTrue | BaseTypeFalse;

function buildCombinedType(
  a: string,
  bAsString: string,
  cAsString: string
): CombinedType {
  if (bAsString === 'true') {
    const c = parseInt(cAsString, 10);

    if (Number.isNaN(c)) {
      throw new Error('cAsString 不是有效数字');
    }

    return { a, b: true, c };
  }

  return { a, b: false, c: undefined };
}

注意两点:

  1. true 分支里直接写 b: true,不要用变量 b。这样 b 的类型是字面量 true,可以匹配 BaseTypeTrue。
  2. true 分支里的 c 必须是 number。示例先 parseInt,再用 Number.isNaN 做运行时校验;发现 NaN 就抛错,免得无效值继续往下传。如果业务上允许 c 为 NaN,去掉 Number.isNaN 判断也能通过类型检查,因为 NaN 的类型还是 number。

如果不需要运行时校验

如果输入已经可信,可以写得更短:

function buildCombinedType(
  a: string,
  bAsString: string,
  cAsString: string
): CombinedType {
  const b = bAsString === 'true';

  if (b) {
    return { a, b: true, c: parseInt(cAsString, 10) };
  }

  return { a, b: false, c: undefined };
}

或者用条件表达式:

function buildCombinedType(
  a: string,
  bAsString: string,
  cAsString: string
): CombinedType {
  return bAsString === 'true'
    ? { a, b: true, c: parseInt(cAsString, 10) }
    : { a, b: false, c: undefined };
}

这两种写法都是让每个分支分别满足判别联合的一个成员。

注意事项

原代码里的解析条件是 cAsString === '' ? parseInt(cAsString, 10) : undefined。这看起来和“有内容才解析成数字”的常见做法相反。如果业务要求 b 为 true 时 c 必须来自 cAsString,建议改成有内容才解析,并校验 NaN。另外,parseInt('12abc', 10) 会得到 12;如果需要严格数字解析,可以改用 Number(cAsString),再配合 Number.isNaN 或更细的校验。

不用给每个字段写 type predicate。type predicate 更适合校验外部输入,或者做用户自定义类型守卫;这里是在构造返回值,直接按判别联合分支返回更自然。

备注:内容仅供参考。