gpt4 book ai didi

typescript - "Cannot invoke an object which is possibly ' 未定义 '"即使在确保它之后!== 未定义

转载 作者:行者123 更新时间:2023-12-04 11:50:00 28 4
gpt4 key购买 nike

为什么我会收到 Cannot invoke an object which is possibly 'undefined'即使在我检查了 func 之后,Typescript 也会出错引用不是未定义的?

type Hoge = {
func?: (str: string) => boolean
}

const myFunc = (obj: Hoge) => {
const data = ['AAA', 'BBB', 'CCC']

if(obj.func !== undefined) {
data.filter(obj.func) // ok
data.filter(v => obj.func(v)) // ng Cannot invoke an object which is possibly 'undefined'.
}
}

最佳答案

知道回调到data.filter立即执行但 typescript 应该如何知道?
考虑这个例子:

type Hoge = {
func?: (str: string) => boolean
}

const myFunc = (obj: Hoge) => {
if(obj.func !== undefined) {
setTimeout(() => obj.func!('a'), 100); // Force assume func is not undefined
}
obj.func = undefined; // TS will allow this since func can be undefined, but this is a problem
}
myFunc({
func: (str: string) => {
console.log(str); return true;
}
})
因为在您的情况下,您确实知道该函数是在 if 块中调用的,您应该使用:
data.filter(v => obj.func!(v))
这会让 TS 知道您知道该函数在那时不是未定义的
Playground link

关于typescript - "Cannot invoke an object which is possibly ' 未定义 '"即使在确保它之后!== 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68371833/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com