typescript - 使用三元运算符时,对象可能为“空”
问题描述
我在 Typescript 4 中有以下内容并使用严格模式:
let userId = parameters.has('userId') ? +parameters.get('userId') : undefined;
我收到编译错误Object is possibly 'null'.
:
+parameters.get('userId')
该方法parameters.get
返回string | null
...
我怎样才能避免这个错误?
解决方案
有几个选项可以解决这个问题,我将从不推荐的内容开始,它是使用 TypeScript 的!
运算符,也称为非空断言
const userId = parameters.has('userId') ? +!parameters.get('userId') : undefined;
这样你就可以告诉 TypeScript 的编译器:“我更了解类型,我保证它不是null
”。不建议使用它,因为该值可能null
在某些条件下。
第二种方法是分成两步,先提取参数再检查是否定义,唯一的缺点是空字符串''
会被转换为undefined
const userIdParam = parameters.get('userId');
const userIdOptionOne = userIdParam ? +userIdParam : undefined;
您可以在这个 TypeScript 游乐场中使用这两个示例
推荐阅读
- database - 如何使用数据库版本控制概念在 Azure SQL 中创建会话,以便两个或多个用户可以在其中进行更改并提交
- python - 使用多处理模块运行并行进程,其中一个由另一个馈送(依赖)用于维特比算法
- c# - 这个语法是什么意思“if (value is bool v)”?
- angular - 如何选择Angular中的所有复选框?
- android - 添加 Admob 模块后反应本机“任务执行失败:':app:processDebugManifest'
- django - ValueError:服务器必须是 Flask 应用程序或布尔值
- google-analytics - 谷歌分析和数据洞察:如何显示同比增长百分比的时间序列
- java - Elasticsearch 乐观锁
- angular - 明确 Angular 中的安全导航运算符
- android - ItemDecoration - 如何创建垂直分隔线?