这是带有 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;
}
如您所见,由于编译错误而找不到元素时,我无法返回 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/