【问题标题】:Type guard for Object (is not null)对象的类型保护(不为空)
【发布时间】:2021-05-14 13:49:50
【问题描述】:

如何在 TypeScript 中为 object 获得类型保护?

我有任何输入的检查功能:

export function isObject(input: any) :input is Record<string,any> {
     return (input !== null) && (typeof input === 'object');
} 

但是当我这样使用它时,编译器不会将我检查的变量视为所需的类型:

const constants = {};
const haveConstantsObj = isObject(constants);

// for constants: Object is possibly 'null'.ts(2531)
if (haveConstantsObj && !constants.householdType) {
    console.log('hey');
}

我做错了什么?

【问题讨论】:

  • 坦率地说,我不知道你为什么首先在这里有一个类型保护。 constants 是用 const 声明的,所以它不可能是 null。这是一个简化的例子吗?如果没有,您可以简单地提供声明:const constants: Record&lt;string,any&gt; = {};。更好的是,让constants实现一个接口interface Consts { householdType ?: &lt;your type here&gt; }不是更好吗?
  • @OlegValter 这个例子很简单,是的。 constants 实际上是异步填充数据的,我需要检查它是否存在。一个不那么抽象的类型在这里可能会有所帮助,但对于像 isObject 这样的对 smth 的必要检查没有帮助。
  • 这么想,感谢您的澄清 - 顺便说一句,constants 对象是否有可能是 nullobject 以外的类型?想建议使用内联 if(constants) 守卫来简化事情,但您已经在 cmets 中提到它(据我记得,手册鼓励在可能的情况下使用内联守卫)。

标签: typescript typeguards


【解决方案1】:

TypeScript 有时有点挑剔。

不要将isObject 的结果保存到变量中,而是将其包含在同一个if 检查中,这样就可以了。

export function isObject(input: any) :input is Record<string,any> {
     return (input !== null) && (typeof input === 'object');
} 

const constants = {};
if (isObject(constants) && !constants.householdType) {
    console.log('hey');
}

TypeScript Playground

【讨论】:

  • 与使用非空断言并将constants 定义为对象相比,这样做会有好处吗? (我还是偶尔打TS类型。)
  • @DaveNewton 当你有一个具体的类型而不是像Record 这样灵活的东西时,这种语法是最有价值的。因此,如果inputstring | { householdType: boolean },则此代码结构更有意义,因为您获得了编译时安全性,并且当isObject 为真时,您只有housholdType
  • 当我想一想:也许我应该放弃 Underscore 对 TypeScript 进行类型检查的方式。我在这里只需要知道constants !== null &amp;&amp; constants !== undefined。或者只是if (constants) ... 我只是不喜欢那些一般检查,对我来说,将这种检查包装在一个函数中仍然是有意义的,但是如果编译器不知道,我知道这个检查是什么,它不会帮助。
  • @BairDev - 这一切都归结为代码流分析。类型保护返回类型谓词 - 关于变量类型的断言。同时,if 之类的控制语句保证在它们的范围内某些东西是真实的。这允许 TS 安全地缩小类型。现在,当您将调用保护的结果分配给变量时,在编译 时唯一可以保证的是该变量现在的类型为boolean。现在控制语句不能保证变量在编译时是其中的某种类型。
  • 是的,正如 Oleg 所说,它 is 在 if 中,而 is not 在 else 中。在其他任何地方,类型都不确定。这没有错,在某些情况下可能非常有价值。有关详细信息,请参阅Type Guards and Differentiating Types
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2019-12-29
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 2021-11-26
相关资源
最近更新 更多