ruxuan1306
V2EX  ›  问与答

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

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

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

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