function printValue(value: string): void;
function printValue(value: number): void;
function printValue(value: boolean): void;
function printValue(value: string | number | boolean) {
if (typeof value ==='string') {
console.log(`字符串: ${value}`);
} else if (typeof value === 'number') {
console.log(`数字: ${value}`);
} else if (typeof value === 'boolean') {
console.log(`布尔值: ${value}`);
}
}
// 类型收缩解释:
// 在函数内部通过typeof进行类型判断,当使用`if (typeof value ==='string')`时,TypeScript能够识别出此时`value`的类型已经收缩为`string`,
// 这样在这个代码块内就可以安全地使用`string`类型相关的属性和方法。同理,在`if (typeof value === 'number')`和`if (typeof value === 'boolean')`
// 代码块内,`value`的类型分别收缩为`number`和`boolean`,使得类型更加精确,从而可以进行针对性的操作而避免类型错误。