You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript函数返回值类型疑问:如何替代Any类型(返回string/boolean)

用联合类型替代Any处理多类型返回值

针对你遇到的函数返回值可能是string或boolean的场景,最佳方案是使用联合类型(string | boolean)来标注返回值类型,完全不需要用any。

正确实现代码

var getValue = (myVal: number): string | boolean => {
    if(myVal > 5){
        return true;
    }
    return "200 OK";
}

为什么这比Any好?

  • 保留类型检查:如果函数里意外返回number等其他类型,TypeScript会直接报错,避免类型隐患
  • 调用时获得类型提示:使用返回值时,TypeScript会提醒你需要处理string和boolean两种情况,比如用类型守卫做区分:
const res = getValue(3);
if (typeof res === 'boolean') {
    // 此处res被推断为boolean类型
    console.log('数值大于5');
} else {
    // 此处res被推断为string类型
    console.log(res);
}

对比之前的问题

  • 不指定返回值时TypeScript推断为any,丢失类型约束,调用时无法获得类型提示
  • 指定单一类型(boolean或string)会直接报错,因为函数确实存在两种返回情况

内容的提问来源于stack exchange,提问作者Ahmed Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:55:31