javascript - 声明允许未定义的导入模块的类型
问题描述
我正在使用一个具有 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。
有没有更好的方法来解决这个问题?
解决方案
当您确定事物已定义时,您可以使用感叹号运算符(非空断言运算符)告诉编译器您知道该值不会为空/未定义。
const thing = someContext.thing!;
推荐阅读
- vue.js - 刷新页面返回后的 Electron Vue:无法获取 /url
- git - Git - CAfile 的不寻常路径
- sql - SQL,GETDATE 在 where 子句中
- python-3.x - 有没有办法使用 Selenium 实现 Magento 图像上传的拖放?
- shell - 定期配置 nginx API
- laravel - Laravel 失败的作业不发送通知
- kubernetes - Kubernetes - 为数据库部署初始化持久卷的最佳方式
- python - ValueError:模型未配置为计算准确性
- python - Python浮点数比较
- c# - AWS S3 PutObjectAsync ETag 不匹配 MD5