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

129 天前
 dcsuibian

第一种:开启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 倒还好,主要是每处调用都要加个!.?.

1043 次点击
所在节点    TypeScript
5 条回复
Trim21
129 天前
开启 strictNullChecks
infyni
129 天前
开启 strictNullChecks 。 有时候后端真的会返回 null
CLMan
128 天前
1. strictNullChecks 肯定得开启吧,开启后 TS 就是 null safe 的语言了
2. 我是去年才学得 TS ,`declare`是不是属于被边缘化的语法,我在 handbook 中没学过,自己项目也从未使用
3. 类型允许 null 就应该增加检测 null 的代码,除非是逻辑需要,不应该用断言`!.`
4. 除开与外界的交互,项目中应该只使用 null 或者 undefined 一种来表示空(google style guide)
hansomeneil
128 天前
老板认可质量,不压缩工期,那就开,否则就别开,短期没有明显好处的事是很敏感、很难推进的。。等什么时候用户的要求提高了再说吧,否则纯粹是给自己增加工作量。。
RedNax
128 天前
不开干嘛还写 TS 。
觉得麻烦写 JS 就好,类型也可以用 jsdocs

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1004887

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX