我的TypeScript属性为什么会抱怨它可能为undefined,当我已经添加了一个检查?

huangapple go评论58阅读模式
英文:

Why is my TypeScript property complaining that it might be undefined when I've already added a check?

问题

代码部分不需要翻译,以下是翻译好的内容:

(property) url?: string | undefined
Argument of type 'string | undefined' is not assignable to parameter of type 'Url'.
  Type 'undefined' is not assignable to type 'Url'.

如果您需要更多帮助,请随时提问。

英文:
const handleClick = (index: number) => () => {
  const hasUrl = !!searchTypes[index]?.url
  if (hasUrl) {
    router.push(searchTypes[index]?.url);
  } else {
    setSelectedSearchType(index);
  }
};

But the error I'm getting is:

(property) url?: string | undefined
Argument of type 'string | undefined' is not assignable to parameter of type 'Url'.
  Type 'undefined' is not assignable to type 'Url'.

答案1

得分: 3

因为TypeScript无法从hasUrl变量的使用推断出该属性的存在。建议写成:

const handleClick = (index: number) => () => {
  const url = searchTypes[index]?.url;
  if (url) {
    router.push(url);
  } else {
    setSelectedSearchType(index);
  }
};

1: 这意味着它没有在编译器中实现,并不是不可能。但!! 让它变得更困难。

英文:

Because TypeScript cannot<sup>1</sup> infer from the usage of the hasUrl variable back to the existence of the property. Prefer to write

const handleClick = (index: number) =&gt; () =&gt; {
  const url = searchTypes[index]?.url
  if (url) {
    router.push(url);
  } else {
    setSelectedSearchType(index);
  }
};

<sub>1: meaning it's not implemented in the compiler, not that it would be impossible. The !! makes it extra hard though.</sub>

答案2

得分: 1

我认为你也可以在变量定义的末尾加上 `!`,以强制类型不为未定义。

const url = searchTypes[index]?.url!


<details>
<summary>英文:</summary>

I think you can also just put a `!` at the end of a variable definition and it forces the type to not be undefined.

const url = searchTypes[index]?.url!



</details>



huangapple
  • 本文由 发表于 2023年2月6日 09:40:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定