首页 > 解决方案 > 使用三元运算符时,对象可能为“空”

问题描述

我在 Typescript 4 中有以下内容并使用严格模式:

let userId = parameters.has('userId') ? +parameters.get('userId') : undefined;

我收到编译错误Object is possibly 'null'.

+parameters.get('userId')

该方法parameters.get返回string | null...

我怎样才能避免这个错误?

标签: typescript

解决方案


有几个选项可以解决这个问题,我将从不推荐的内容开始,它是使用 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 游乐场中使用这两个示例


推荐阅读