以下是启用 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,因为会发生编译错误:
错误:'null' 无法赋值给类型 'T'
我该返回什么而不是null呢?有什么最佳实践吗?
null
呢?例如:getItem(key: string): T | null { ... }
? - CRiceT
或null
?getItem(key: string): T | null
- 顺带一提,我从不在JavaScript / TypeScript中使用null
: https://github.com/Microsoft/TypeScript/issues/8940 - random_user_namefalse
或undefined
。我相信这是“最佳实践”,但没有权威来源支持这种信念。一些数据点:https://github.com/Microsoft/TypeScript/issues/8940和https://www.thecodeship.com/web-development/the-undefined-vs-null-pitfall-in-javascript/和https://dev59.com/xWw15IYBdhLWcg3wcrZC#28825847 - 使用null需要额外的工作/复杂性来检查值... - random_user_name