← 中文资源

简体中文版本

真值判断收窄联合类型而非基本类型

真值判断能把空串、undefined 这类假值成员从字面量联合里剔除,但普通 number 在两个分支里都还是 number:想单独处理零只能写显式相等比较。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

size sm with count 2
no size; count is zero
no size; count 5
defined names: ada,bo
kept by !== 0: 1,2
truthy only: 1,2

实现说明

真值判断收窄联合类型而非基本类型以函数 render为骨架。

使用要点

  • 守卫 size 成立时借助提前的 return 直接离开。
  • 直接运行文件,输出会带上标签,比如 defined names:、kept by !== 0:、truthy only:——输出的每一行都能指回产生它的那次调用。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 render。

签名一览:function render({ size, count }: Draft)

核心语句

return `no size; count ${count === 0 ? 'is zero' : count}`;
const defined = names.filter((name) => name !== undefined);
return `size ${size} with count ${count}`;

代码示例

type Draft = { size: '' | 'sm' | 'lg' | undefined; count: number };

function render({ size, count }: Draft): string {
  // Truthiness drops '' and undefined: size is 'sm' | 'lg' here
  if (size) {
    return `size ${size} with count ${count}`;
  }
  // count stays number in both branches — zero is not a literal member,
  // so an explicit comparison is the only way to single it out
  return `no size; count ${count === 0 ? 'is zero' : count}`;
}

console.log(render({ size: 'sm', count: 2 }));
console.log(render({ size: '', count: 0 }));
console.log(render({ size: undefined, count: 5 }));

// On plain-typed arrays, truthiness filters only null and undefined members
const names: (string | undefined)[] = ['ada', undefined, 'bo'];
const defined = names.filter((name) => name !== undefined);
console.log('defined names:', defined.join(','));

const counts: number[] = [0, 1, 2];
console.log('kept by !== 0:', counts.filter((n) => n !== 0).join(','));
console.log('truthy only:', counts.filter(Boolean).join(','));