V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
ruxuan1306
V2EX  ›  问与答

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

  •  
  •   ruxuan1306 · Dec 31, 2022 · 1219 views
    This topic created in 1214 days ago, the information mentioned may be changed or developed.
    3 replies    2023-01-04 15:01:16 +08:00
    KMpAn8Obw1QhPoEP
        1
    KMpAn8Obw1QhPoEP  
       Dec 31, 2022 via Android   ❤️ 1
    因为去掉第一行判断 逻辑依然成立吧
    最后 a+b 的时候两者类型都是 number 没什么问题
    你把第二行判断和第三行调换一下 结果也是一样的
    还可以写成

    if (a!==null &&b!==null) return a+b;
    return a??b;
    TWorldIsNButThis
        2
    TWorldIsNButThis  
       Dec 31, 2022
    直接嵌套 if
    不整这些 early return

    if + else 是完备( exhaustive )的而 early return 不一定是,比如第一句
    LLaMA2
        3
    LLaMA2  
       Jan 4, 2023
    if(a && b) { return a + b}
    else {return a ?? b}
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1004 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 19:19 · PVG 03:19 · LAX 12:19 · JFK 15:19
    ♥ Do have faith in what you're doing.