V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
dcsuibian
V2EX  ›  TypeScript

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

  •  
  •   dcsuibian · 117 天前 · 1004 次点击
    这是一个创建于 117 天前的主题,其中的信息可能已经有所发展或是发生改变。

    第一种:开启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 条回复    2024-01-02 00:42:21 +08:00
    Trim21
        1
    Trim21  
       117 天前 via Android
    开启 strictNullChecks
    infyni
        2
    infyni  
       117 天前   ❤️ 2
    开启 strictNullChecks 。 有时候后端真的会返回 null
    CLMan
        3
    CLMan  
       117 天前
    1. strictNullChecks 肯定得开启吧,开启后 TS 就是 null safe 的语言了
    2. 我是去年才学得 TS ,`declare`是不是属于被边缘化的语法,我在 handbook 中没学过,自己项目也从未使用
    3. 类型允许 null 就应该增加检测 null 的代码,除非是逻辑需要,不应该用断言`!.`
    4. 除开与外界的交互,项目中应该只使用 null 或者 undefined 一种来表示空(google style guide)
    hansomeneil
        4
    hansomeneil  
       116 天前
    老板认可质量,不压缩工期,那就开,否则就别开,短期没有明显好处的事是很敏感、很难推进的。。等什么时候用户的要求提高了再说吧,否则纯粹是给自己增加工作量。。
    RedNax
        5
    RedNax  
       116 天前 via iPhone
    不开干嘛还写 TS 。
    觉得麻烦写 JS 就好,类型也可以用 jsdocs
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2936 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 08:01 · PVG 16:01 · LAX 01:01 · JFK 04:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.