typescript - 即使我有一个用户定义的类型保护来检查它是否不是,值也可能是未定义的
问题描述
在下面的代码中,我使用用户定义的类型保护来检查val
未定义的(如果是则提前返回)。类型脚本编译器似乎没有意识到这一点。当我尝试将val
其用作字符串时收到警告Object is possibly 'undefined
。
function isUndefined(val: any): val is undefined {
return typeof val === "undefined";
}
function calculateFontSize(el: SVGElement) {
const val = getPresentationAttribute(el, "font-size");
if (isUndefined("val")) {
return null;
}
// const val: string | undefined; Object is possibly 'undefined'.
return Number.parseFloat(val.replace("px", ""));
}
为什么 TypeScript 不能从我的用户定义的类型保护中获取类型?
解决方案
传入val
,而不是"val"
:
if (isUndefined(val)) {
return null;
}
推荐阅读
- python - 导入数据直到特定行
- lotus-domino - 用于从 Excel 文件中删除大量 domino 目录用户的 Lotus 脚本
- python - 字符串转换和编码
- python - 你能找出这里的错误吗?
- video - 视频在 Chrome 中运行之前,我的网站中有奇怪的垂直线
- nginx - Nginx 正则表达式 pcre_compile() 失败
- assembly - 正确的寻址方式
- mobile - 将大型复杂的 3D 场景带入移动设备,请帮助我们提出您的想法![没有限制]
- swift - 将collectionView连接到tableView
- javascript - 点赞按钮怎么实现?