我正在尝试键入这样的代码
type MyObj = {
someProp?: string
}
function getStuff(obj: MyObj): string {
return 'hello ' + obj.someProp
}
let x
if (obj.someProp) {
x = getStuff(obj)
}
但是类型检查器抱怨在
getStuff
,
obj.someProp
可能未定义。我真的必须做两次运行时检查吗?我只是重新编写代码来办理登机手续吗
getStuff()
type MyObj = {
someProp?: string
}
function getStuff(obj: MyObj): string | undefined {
if (obj.someProp === undefined) {
return undefined
}
return 'hello ' + obj.someProp
}
const x = getStuff(obj)
或者还有别的办法吗?