【问题标题】:Typescript: use type declaration to force a null-check?打字稿:使用类型声明强制进行空检查?
【发布时间】:2020-12-25 03:21:34
【问题描述】:

我知道你可以在 typescript 中声明 type as nullable

但这并不强制用户进行空检查,例如

function maybeReturnString(): string | null { ... }
function getOnlyString(str: string) { ... }

const maybeString = maybeReturnString();
getOnlyString(maybeString) // OK

如果我不检查 null,使构建失败的正确方法是什么?

有没有类似于 Scala 中的 Option[String] 或 Kotlin 中的 String? 的东西?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我不确定您正在运行哪个版本的 TypeScript,但这肯定会引发编译时错误,如 playground 中所示(使用您自己的代码)。

    要回答您的其他问题,您还可以使用与string | undefined 等效的string? 语法。

    【讨论】:

    • 奇怪,检查
    【解决方案2】:

    我的问题是我没有设置配置strictNullChecks=true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-06
      • 2021-04-09
      • 2019-02-16
      • 1970-01-01
      • 2021-05-12
      • 2022-01-06
      • 2017-08-12
      • 2021-01-20
      相关资源
      最近更新 更多