首页 > 解决方案 > 即使我有一个用户定义的类型保护来检查它是否不是,值也可能是未定义的

问题描述

在下面的代码中,我使用用户定义的类型保护来检查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 不能从我的用户定义的类型保护中获取类型?

标签: typescript

解决方案


传入val,而不是"val"

  if (isUndefined(val)) {
    return null;
  }

推荐阅读