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

想问问大家 TypeScript 中关于 null 处理的方式

  •  
  •   dcsuibian · Jan 1, 2024 · 2261 views
    This topic created in 848 days ago, the information mentioned may be changed or developed.

    第一种:开启strictNullChecks

    interface C {
      foo: string;
    }
    interface B {
      c: C | null;
    }
    interface A {
      b: B | null;
    }
    
    declare const a: A;
    
    console.log(a.b!.c!.foo)
    

    第二种:关闭strictNullChecks

    interface C {
      foo: string;
    }
    interface B {
      c: C;
    }
    interface A {
      b: B;
    }
    
    const a: A = {
      b: null,
    };
    

    大家更倾向于哪一种呢?

    我个人现在用的第一种,但总感觉很麻烦。类型声明时要加个 null 倒还好,主要是每处调用都要加个!.?.

    5 replies    2024-01-02 00:42:21 +08:00
    Trim21
        1
    Trim21  
       Jan 1, 2024 via Android
    开启 strictNullChecks
    infyni
        2
    infyni  
       Jan 1, 2024   ❤️ 2
    开启 strictNullChecks 。 有时候后端真的会返回 null
    CLMan
        3
    CLMan  
       Jan 1, 2024
    1. strictNullChecks 肯定得开启吧,开启后 TS 就是 null safe 的语言了
    2. 我是去年才学得 TS ,`declare`是不是属于被边缘化的语法,我在 handbook 中没学过,自己项目也从未使用
    3. 类型允许 null 就应该增加检测 null 的代码,除非是逻辑需要,不应该用断言`!.`
    4. 除开与外界的交互,项目中应该只使用 null 或者 undefined 一种来表示空(google style guide)
    hansomeneil
        4
    hansomeneil  
       Jan 1, 2024
    老板认可质量,不压缩工期,那就开,否则就别开,短期没有明显好处的事是很敏感、很难推进的。。等什么时候用户的要求提高了再说吧,否则纯粹是给自己增加工作量。。
    RedNax
        5
    RedNax  
       Jan 2, 2024 via iPhone
    不开干嘛还写 TS 。
    觉得麻烦写 JS 就好,类型也可以用 jsdocs
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5838 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 68ms · UTC 06:08 · PVG 14:08 · LAX 23:08 · JFK 02:08
    ♥ Do have faith in what you're doing.