V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
ruxuan1306
V2EX  ›  问与答

为什么 TypeScript 在第二行还会认为 b 可为 null?应该怎样写更好?

  •  
  •   ruxuan1306 · 2022-12-31 15:08:10 +08:00 · 779 次点击
    这是一个创建于 482 天前的主题,其中的信息可能已经有所发展或是发生改变。
    3 条回复    2023-01-04 15:01:16 +08:00
    enchilada2020
        1
    enchilada2020  
       2022-12-31 15:31:27 +08:00 via Android   ❤️ 1
    因为去掉第一行判断 逻辑依然成立吧
    最后 a+b 的时候两者类型都是 number 没什么问题
    你把第二行判断和第三行调换一下 结果也是一样的
    还可以写成

    if (a!==null &&b!==null) return a+b;
    return a??b;
    TWorldIsNButThis
        2
    TWorldIsNButThis  
       2022-12-31 15:33:52 +08:00
    直接嵌套 if
    不整这些 early return

    if + else 是完备( exhaustive )的而 early return 不一定是,比如第一句
    LLaMA2
        3
    LLaMA2  
       2023-01-04 15:01:16 +08:00
    if(a && b) { return a + b}
    else {return a ?? b}
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2724 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:30 · PVG 10:30 · LAX 19:30 · JFK 22:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.