首页 > 解决方案 > 声明允许未定义的导入模块的类型

问题描述

我正在使用一个具有 TS def 的模块,例如:

// index.d.ts

interface SomeContext {
  // ... other props

  thing?: Record<string, any>;
}

当我们使用这个模块时,我们会注意someContext.thing被定义,所以当我们开始使用它时它永远不会未定义。我们想在我们的代码中给它我们自己的类型,因为我们会知道形状是什么,但必须执行以下操作才能让它通过 TS 构建:

const { thing: ourThing } = <{ thing: any }>someContext.thing;

这感觉像是错误的做法,因为我们失去了 TS 通常给我们的安全和 DX。

有没有更好的方法来解决这个问题?

标签: javascripttypescripttypescasting

解决方案


当您确定事物已定义时,您可以使用感叹号运算符(非空断言运算符)告诉编译器您知道该值不会为空/未定义。

const thing = someContext.thing!;


推荐阅读