【问题标题】:TS2531: Object is possibly 'null' even if I check that it is notTS2531:对象可能是“空”,即使我检查它不是
【发布时间】:2020-08-11 02:38:00
【问题描述】:

我从 TS 编译器得到这个错误:“TS2531: Object is possible 'null'” in the following code:

const routeParamsCheck = (
  routeParams: unknown
): routeParams is { slug: string; locale: string } => {
  return (
    routeParams !== null &&
    typeof routeParams === 'object' &&
    'slug' in routeParams &&
    'locale' in routeParams
  );
};

我想知道为什么它会发生在这一行:'slug' in routeParams(对我来说很明显,此时 routeParams 不能为空)。重写此代码的正确方法是什么。谢谢!

【问题讨论】:

  • 仅供参考,这是已知的打字稿issue

标签: typescript


【解决方案1】:

显然,在routeParams !== null 行之后,typescript 仍然认为类型是unknown。即,就类型而言,没有任何变化。我不确定这是为什么(可能是 unknown 类型的错误或已知限制),但您可以做一个非常简单的修复:只需交换前两行的顺序:

  return (
    typeof routeParams === 'object' &&
    routeParams !== null &&
    'slug' in routeParams &&
    'locale' in routeParams
  );

这样第一行会将unknown 缩小为object | null,而object | null 可以通过第二行缩小为object

【讨论】:

    猜你喜欢
    • 2018-12-27
    • 2021-02-14
    • 2021-10-21
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2021-07-11
    相关资源
    最近更新 更多