实现说明
真值判断收窄联合类型而非基本类型以函数 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(','));