javascript - 使用严格模式在 TypeScript 中找不到对象时应该返回什么?

标签 javascript typescript strictnullchecks

这是带有 strictNullChecks: true

的 typescript 代码片段
getItem(key: string): T {
    let index: number = this.contains(key); // returns -1 if not found
    if (index === -1) {
        return null; // error null is not assignable to type 'T'
    } 
    return this.map[index].value;
  }

如您所见,由于编译错误而找不到元素时,我无法返回 null:

error 'null' is not assignable to type 'T'

我应该返回什么而不是 null?最佳做法是什么?

最佳答案

通过严格的空值检查,任何返回可能“未找到”的东西的函数都应该将返回类型声明为 Something | undefined,它应该在“未找到”的情况下返回 undefined 值。

也可以使用 null 而不是 undefined 作为类型和返回值,但是做出了选择,TypeScript 类型系统使用 undefined,而不是 null 表示未初始化和可选的值 - 例如,可选属性的类型(用 ? 符号声明)是 T |未定义

另见 this quote用户 cale_b 在评论中提到:

the rational is JavaScript has two concepts to refer to the empty sentinel value, most other programming languages just have one. Moreover, undefined is always present, as all uninitialized values have the value undefined at run time. null on the other hand is avoidable, specially if you are not using any APIs that produce it, e.g. DOM, which the TypeScript compiler does not use.

关于javascript - 使用严格模式在 TypeScript 中找不到对象时应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50262246/

相关文章:

Javascript - 使用 innerHTML 替换 html

javascript - 将范围添加到 Angular-Seed 默认 View Controller 时,测试套件现在失败

angular - 如何在 Angular 4 中实现 strictNullChecks

javascript - Best In Place 不是一个功能 Rails 5

javascript - 扩展数据表 "fnInitComplete"?

Angular2 排序数组,用于在 html 中的 *ngFor 中显示

typescript - 更好的 typescript 文件引用

typescript - 如何更新 React/TypeScript 项目中的快照?

typescript - 为什么 TypeScript 在使用 concat 缩减数组时会推断出 'never' 类型?

javascript - typescript :使用 Map<> with strictNullChecks