【发布时间】:2018-05-09 21:21:18
【问题描述】:
这是带有strictNullChecks: true的打字稿中代码的sn-p
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:
错误“null”不能分配给类型“T”
我应该返回什么而不是 null?最佳做法是什么?
【问题讨论】:
-
为什么不直接更改返回类型注释以包含
null?例如:getItem(key: string): T | null { ... }? -
让函数返回
Tor null 怎么样?getItem(key: string): T | null- 作为旁注,我从来没有,ever 在 javascript / typescript 中使用null:github.com/Microsoft/TypeScript/issues/8940 -
这是最佳实践吗?当你从不使用 null 时,你用什么代替 null ?
-
在您的具体示例中,我将使用
false或undefined,具体取决于您的地图内容。我相信这是“更好的实践”,但没有该信念的权威来源。一些数据点:github.com/Microsoft/TypeScript/issues/8940 和 thecodeship.com/web-development/… 和 stackoverflow.com/a/28825847 - 检查值时使用 null 需要额外的工作/复杂性...
标签: javascript typescript strictnullchecks