【问题标题】:Declare type for imported module that allows undefined声明允许未定义的导入模块的类型
【发布时间】:2021-10-02 13:42:12
【问题描述】:

我正在使用一个具有类似 TS def 的模块:

// index.d.ts

interface SomeContext {
  // ... other props

  thing?: Record<string, any>;
}

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

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

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

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

【问题讨论】:

    标签: javascript typescript types casting


    【解决方案1】:

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

    const thing = someContext.thing!;

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多