英文:
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) => () => {
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论