【问题标题】:What should I return when object is not found in TypeScript using strict mode?使用严格模式在 TypeScript 中找不到对象时应该返回什么?
【发布时间】: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 { ... }?
  • 让函数返回T or null 怎么样? getItem(key: string): T | null - 作为旁注,我从来没有,ever 在 javascript / typescript 中使用 nullgithub.com/Microsoft/TypeScript/issues/8940
  • 这是最佳实践吗?当你从不使用 null 时,你用什么代替 null ?
  • 在您的具体示例中,我将使用falseundefined,具体取决于您的地图内容。我相信这是“更好的实践”,但没有该信念的权威来源。一些数据点:github.com/Microsoft/TypeScript/issues/8940thecodeship.com/web-development/…stackoverflow.com/a/28825847 - 检查值时使用 null 需要额外的工作/复杂性...

标签: javascript typescript strictnullchecks


【解决方案1】:

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

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

另见用户cale_b在cmets中提到的this quote

有理是JavaScript有两个概念来指代空 哨兵值,大多数其他编程语言只有一个。 此外, undefined 始终存在,因为所有未初始化的值 在运行时具有未定义的值。另一方面, null 是 可以避免的,特别是如果您不使用任何生成它的 API, 例如DOM,TypeScript 编译器不使用它。

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2019-07-08
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多