如何在对象永远不为空时将 "TS2531: Object is possibly 'null'" 错误标记为误报?

How to tag a "TS2531: Object is possibly 'null'" when the object is never null" error as a false positive?

以下代码

const infinoteUrl =
  $q.localStorage.getItem("infinote-dev-api") === null
    ? `${window.location.protocol}//${window.location.host}`
    : $q.localStorage.getItem("infinote-dev-api")
console.log(`infinote URL: ${infinoteUrl}`)

let infinoteToken = $q.localStorage.getItem("infinote-token")
if (infinoteToken === null && !infinoteUrl.toString().includes("localhost")) {
   ...
}

编译时出现 TS2531: Object is possibly 'null' 错误:

TS2531: Object is possibly 'null'.
    106 |
    107 |     let infinoteToken = $q.localStorage.getItem("infinote-token")
  > 108 |     if (infinoteToken === null && !infinoteUrl.toString().includes("localhost")) {
        |                                    ^^^^^^^^^^^
    109 |       infinoteToken = "empty"
    110 |       $q.notify({
    111 |         message: 'no infinote-token in local storage',

我不相信 infinoteUrl 会变成 null 所以我想告诉编译器这种情况没问题。有办法吗?

至于问题本身,感谢 Optional Chaining (if (infinoteToken === null && !infinoteUrl?.toString().includes("localhost"))),我解决了它,但是 我感兴趣的是如何更普遍地告诉 TS 编译器一个案例检测到错误警报

使用@ts-ignore

// @ts-ignore TS2531: Object is possibly 'null'
if (infinoteToken === null && !infinoteUrl.toString().includes("localhost"))

这将忽略注释下方行中的 所有 错误(因此即使值永远不会 null 也使用可选链接会更安全)

您可以使用 ! non-null assertion operator.

if (infinoteToken === null && !infinoteUrl!.toString().includes("localhost")) {

您假设 infinoteUrl 不能为空,因为您假设 $q.localStorage.getItem("infinote-dev-api") 将 return 相同值的两倍。但这没有语法保证。因此 TypeScript 警告你。您可以按照建议使用 !.,但在我看来,这首先违背了使用严格类型系统的意义。尝试利用打字稿的功能。您可以将其重写为

const maybeInfinoteUrl = $q.localStorage.getItem("infinote-dev-api");
const infinoteUrl =
   maybeInfinoteUrl === null
    ? `${window.location.protocol}//${window.location.host}`
    : maybeInfinoteUrl
console.log(`infinote URL: ${infinoteUrl}`)

或更简单的形式(基本上可以编译成类似的形式)是

const infinoteUrl =
  $q.localStorage.getItem("infinote-dev-api")
    ?? `${window.location.protocol}//${window.location.host}`

console.log(`infinote URL: ${infinoteUrl}`)

这里有一个 TypeScript Plaground 示例:https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAcwKZQGoEMA2JUAUAlAFyJgg46IA+iAzlAE4xjKIDeAUIr4k+hBMkAciz0AJsBEBuLgF8uXCAkaIAHogC8KdNjyEi2rTopVEAfkQiAjgHdUTEYjJpMufMTkqwagJ7auu4GxJZWtg5OcsqqcDioAHQ4cMgE6glQcAAycJEAwuKGRN6x8UkpBH4Z2bmOBfRFMkA