当使用严格模式在 TypeScript 中找不到对象时,我应该 return 怎么办?

What should I return when object is not found in TypeScript using strict mode?

这是带有 strictNullChecks: true

的打字稿代码片段
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;
  }

如您所见,由于编译错误而找不到元素时,我不能 return null:

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

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

通过严格的空值检查,任何 returning 可能是 'not found' 的函数都应该将 return 类型声明为 Something | undefined,并且它应该 return undefined "not found" 案例中的值。

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

另见 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.